Live survey304 models · 14 providers · 22,792 auditsAudited grill-with-docs · SAFE →What changedHow we verifyllms.txt

Agent skill · Audited from source

dart-generate-test-mocks

skill · dart-lang/skillsBSD-3-Clause licenceAudited 24 Oct 2026 · source db37821a6b02

★ 530pushed 7 days ago
✓SAFEGrade B · 89/100 · 24 Oct 2026 · db37821
530repo stars · whole dart-lang/skills

Is it safe? Yes — SAFE, grade B (89/100). We read this skill's source at commit db37821a6b02 and found no filesystem, network or shell access and no hard-coded secrets. What it does: Define and generate mock objects for external dependencies using `package:mockito` and `build_runner`. Use when unit testing classes that depend on complex external services like APIs or databases.

Ask an AI about this pageGChatGPTCClaudePPerplexityGeGeminiXGrok
More
Cite

Cite this page

ModelsAtlas. “dart-generate-test-mocks (dart-lang/skills)”. Retrieved 24 Oct 2026. https://modelsatlas.com/skills/dart-lang/dart-generate-test-mocks

2 skills are called “dart-generate-test-mocks”. You are viewing dart-lang/skills.

Trust audit

Audit 0.4.1 · source read 24 Oct 2026

Trust score89/100✓SAFE B
0 critical0 high0 medium0 low0 info

SAFE means nothing in the source contradicts what the skill says it does. Grade B is shared by 16,667 of 17,602 audited skills.

What the source does

  • FilesystemNone observedNo reads or writes in the source
  • NetworkNone observedNo outbound calls in the source
  • ShellNone observedNo commands run in the source
  • DependenciesPinnedNothing floats
  • SecretsNone foundNo keys in source

Five audit layers

LayerWhat we checkResultFindings
L0 ProvenanceRepo owner, licence, archive status, activityPASS0
L1 Static sourceSecrets, path traversal, supply chain, hidden codeNA0
L2 InstructionsPrompt injection, authority framing, hidden directivesPASS0
L3 InventoryThe files and declarations match the sourcePASS0
L4 SandboxRun in isolation and watch behaviourSKIPPED why0

Gates applied: no behavioural pass.

Findings (0)

No findings at any severity. We re-audit when the source changes.

Audit 0.4.1 · source sha db37821a6b02 · 24 Oct 2026Report an issue or request a re-scan

Provenance

Who published it, and what the verdict is pinned to

  • Publisherdart-lang GitHub organizationOwner of the repository this skill is read from
  • Source folderdart-lang/skills/skills/dart-generate-test-mocksThe exact folder we audited
  • LicenceBSD-3-ClauseAs the repository states it
  • Commit pinned for this verdictdb37821a6b02A new audit runs when the source changes
  • Repository statusNot archivedLast push 7 days ago
  • Sandboxed runNot runSkills are read, not executed; layer L4 is skipped

What it tells the agent

Full source on GitHub ↗

Its description: Define and generate mock objects for external dependencies using `package:mockito` and `build_runner`. Use when unit testing classes that depend on complex external services like APIs or databases.

---
name: dart-generate-test-mocks
description: Define and generate mock objects for external dependencies using `package:mockito` and `build_runner`. Use when unit testing classes that depend on complex external services like APIs or databases.
metadata:
  model: models/gemini-3.1-pro-preview
  last_modified: Fri, 24 Apr 2026 15:13:58 GMT
---
# Testing and Mocking Dart Applications

## Contents
- [Structuring Code for Testability](#structuring-code-for-testability)
- [Managing Dependencies](#managing-dependencies)
- [Generating Mocks](#generating-mocks)
- [Implementing Unit Tests](#implementing-unit-tests)
- [Workflow: Creating and Running Mocked Tests](#workflow-creating-and-running-mocked-tests)
- [Examples](#examples)

## Structuring Code for Testability
Design Dart classes to support dependency injection. Isolate complex external dependencies (like API clients or databases) so they can be replaced with mock objects during testing.

- Inject external services (e.g., `http.Client`) through class constructors.
- Represent URLs strictly as `Uri` objects using `Uri.parse(string)`.
- Utilize Dart's object-oriented features (classes, mixins) to define clear interfaces for external interactions.

## Managing Dependencies
Configure the `pubspec.yaml` file with the necessary testing and code generation packages.

- Add runtime dependencies (e.g., `package:http`) using `dart pub add http`.
- Add testing dependencies using `dart pub add dev:test dev:mockito dev:build_runner`.
- Import HTTP libraries with a prefix to avoid namespace collisions: `import 'package:http/http.dart' as http;`.

## Generating Mocks
Use `package:mockito` and `build_runner` to automatically generate mock classes for fixed scenarios and behavior verification.

- Always use the `@GenerateNiceMocks` annotation (preferable to `@GenerateMocks` to avoid missing stub exceptions).
- Place the annotation in the test file, passing a list of `MockSpec<Type>()` objects.
- Import the generated file using the `.mocks.dart` extension.
- Execute `build_runner` to generate the mock files: `dart run build_runner build`.

## Implementing Unit Tests
Isolate the system under test using the generated mock objects. Use `package:test` to structure the test suite.

- **Stubbing:** Configure mock behavior before interacting with the system under test.
  - Use `when(mock.method()).thenReturn(value)` for synchronous methods.
  - **CRITICAL:** Always use `thenAnswer((_) async => value)` for methods returning a `Future` or `Stream`. Never use `thenReturn` for asynchronous returns.
- **Verification:** Assert that the system under test interacted with the mock object correctly.
  - Use `verify(mock.method()).called(1)` to check exact invocation counts.
  - Use argument matchers like `any`, `anyNamed`, or `captureAny` for flexible verification.

## Workflow: Creating and Running Mocked Tests

Use the following checklist to implement and verify mocked unit tests.

### Task Progress
- [ ] 1. Identify the external dependency to mock (e.g., `http.Client`).
- [ ] 2. Inject the dependency into the target class constructor.
- [ ] 3. Create a test file (e.g., `target_test.dart`) and add `@GenerateNiceMocks([MockSpec<Dependency>()])`.
- [ ] 4. Add the `part` or `import` directive for the generated `.mocks.dart` file.
- [ ] 5. Run `dart run build_runner build` to generate the mock classes.
- [ ] 6. Write the test cases using `group()` and `test()`.
- [ ] 7. Stub required behaviors using `when()`.
- [ ] 8. Execute the target method.
- [ ] 9. Verify interactions using `verify()` and assert outcomes using `expect()`.
- [ ] 10. Run the test suite using `dart test`.

### Feedback Loop: Test Failures
If tests fail or `build_runner` encounters errors:
1. **Run validator:** Execute `dart test` or `dart run build_runner build`.
2. **Review errors:** Check for missing stubs, mismatched argument matchers, or syntax errors in the generated files.
3. **Fix:**
   - If a mock method throws an unexpected null error, ensure you used `@GenerateNiceMocks`.
   - If an async stub throws an `ArgumentError`, change `thenReturn` to `thenAnswer`.
   - If `build_runner` fails, ensure the `.mocks.dart` import matches the file name exactly.
4. Repeat until all tests pass.

## Examples

### High-Fidelity Mocking and Testing Example

**1. System Under Test (`lib/api_service.dart`)**
```dart
import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiService {
  final http.Client client;

  ApiService(this.client);

  Future<String> fetchData(String urlString) async {
    final uri = Uri.parse(urlString);
    final response = await client.get(uri);

    if (response.statusCode == 200) {
      return jsonDecode(response.body)['data'];
    } else {
      throw Exception('Failed to load data');
    }
  }
}
```

**2. Test Implementation (`test/api_service_test.dart`)**
```dart
import 'package:test/test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:http/http.dart' as http;
import 'package:my_app/api_service.dart';

// Generate the mock class for http.Client
@GenerateNiceMocks([MockSpec<http.Client>()])
import 'api_service_test.mocks.dart';

void main() {
  group('ApiService', () {
    late ApiService apiService;
    late MockClient mockHttpClient;

    setUp(() {
      mockHttpClient = MockClient();
      apiService = ApiService(mockHttpClient);
    });

    test('returns data if the http call completes successfully', () async {
      // Arrange: Stub the async HTTP GET request using thenAnswer
      when(mockHttpClient.get(any)).thenAnswer(
        (_) async => http.Response('{"data": "Success"}', 200),
      );

      // Act
      final result = await apiService.fetchData('https://api.example.com/data');

      // Assert
      expect(result, 'Success');

      // Verify the mock was called with the correct Uri
      verify(mockHttpClient.get(Uri.parse('https://api.example.com/data'))).called(1);
    });

    test('throws an 

Excerpt, first 6,000 characters of SKILL.md, verbatim from the audited commit. It is text from someone else’s repository, quoted so you can judge it before your agent reads it.

Install

Pinned to the audited commit db37821

Download folder ↗
git clone https://github.com/dart-lang/skills
git -C skills checkout db37821a6b02

The author documents no install command, so this uses the repository directly. Our verdict covers commit db37821a6b02 only.

Works in

The author has not said which agents this skill supports, and we have not tested it in any.

Audit history

Every audit, every source change

  1. ✓SAFE B 89 / 100

    first audit · source db37821a6b02

Questions about dart-generate-test-mocks

Is dart-generate-test-mocks safe to install?
The audit found nothing in the source that contradicts what it says it does, and graded it B (89/100). Grade A is held back for packages that have also passed a sandboxed behavioural run, which is why a clean skill reads B.
What can dart-generate-test-mocks access on my machine?
The audit observed no filesystem, network or shell use at all in its source.
How current is this page?
The grade is for one exact copy of the source (db37821a6b02), read on 2026-10-24. The repository is watched, and a new audit runs when it changes — this is the first audit.

Sources

Spotted something wrong? Report a correction · Methodology

Keep going in your AI

Opens with this page as the source. We add nothing else to the prompt.