dart-generate-test-mocks
Skill4 starsChanged 4 months agoMITView on GitHub
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.
5 other projects use a version of this.
Adopted by
Most recently taken up by
- dart-lang/skillsword for word, first seen Oct 16, 2026
- zhouycheng/skillsword for word, first seen Oct 13, 2026
- enrique-lozano/Monekinword for word, first seen Oct 9, 2026
- flutter/skillsword for word, first seen Oct 8, 2026
- RodotDev/arb_aiword for word, first seen May 30, 2026
Used with
Projects with it also use dart-use-doc-examples and dart-write-documentation.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
flutterSkilldart-use-doc-examples
How to inject external code examples into Dartdoc using the {@example} directive, and how to filter those files using #hide, #region, and #endregion tags.
Also in 3 projects that use this
flutterSkilldart-write-documentation
Rules and formatting guidelines for writing Dart /// API documentation and doc comments. Use when documenting Dart code, writing doc comments for any Dart declaration (libraries, classes, methods, variables, etc.), or when instructed to follow the Effective Dart documentation guidelines.
Also in 3 projects that use this
Other versions5 projects use a version of this.
Word for word · 5
- flutter/skills★ 3.2k100% same
- dart-lang/skills★ 548100% same
- enrique-lozano/Monekin★ 268100% same
- RodotDev/arb_ai★ 1100% same
- zhouycheng/skills★ 1100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository70 other files it gives its agents.
- AGENTS.mdAGENTS.md
- engine/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- engine/CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- brandkitSkill
- code-reviewSkill
- dart-add-unit-testSkill
- dart-build-cli-appSkill
- dart-collect-coverageSkill
- dart-fix-runtime-errorsSkill
- dart-migrate-to-checks-packageSkill
- dart-resolve-package-conflictsSkill
- dart-run-static-analysisSkill
- dart-setup-ffi-assetsSkill
- dart-use-ffigenSkill
- dart-use-pattern-matchingSkill
- dart-use-primary-constructorsSkill
- design-taste-frontendSkill
- flutter-add-integration-testSkill
- flutter-add-widget-previewSkill
- flutter-add-widget-testSkill
- flutter-apply-architecture-best-practicesSkill
- flutter-build-responsive-layoutSkill
- flutter-fix-layout-issuesSkill
- flutter-implement-json-serializationSkill
- flutter-setup-declarative-routingSkill
- flutter-setup-localizationSkill
- flutter-use-http-packageSkill
- frontend-code-reviewSkill
- full-output-enforcementSkill
- github-releaseSkill
- grill-with-docsSkill
- high-end-visual-designSkill
- imagegen-frontend-webSkill
- image-to-codeSkill
- improve-codebase-architectureSkill
- industrial-brutalist-uiSkill
- minimalist-uiSkill
- redesign-existing-projectsSkill
- source-command-frontend-code-review-skillSkill
- source-command-impeccable-skillSkill
- stitch-design-tasteSkill
- tddSkill
- to-prdSkill
- frontend-code-reviewSkill
- impeccableSkill
- dart-add-unit-testSkill
- dart-build-cli-appSkill
- dart-collect-coverageSkill
- dart-fix-runtime-errorsSkill
- dart-generate-test-mocksSkill
- dart-migrate-to-checks-packageSkill
- dart-resolve-package-conflictsSkill
- dart-run-static-analysisSkill
- dart-setup-ffi-assetsSkill
- dart-use-ffigenSkill
- dart-use-pattern-matchingSkill
- dart-use-primary-constructorsSkill
- flutter-add-integration-testSkill
- The first 60 shown.
The file
Show its rules and text
We split this skill into the rules it gives an agent
17 rules. About 0 are common, 2 are distinctive, and 15 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
15
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 28
Add runtime dependencies (e.g., package:http) using dart pub add http.
- Very specific: line 29
Add testing dependencies using dart pub add dev:test dev:mockito dev:build_runner.
- Very specific: line 30
Import HTTP libraries with a prefix to avoid namespace collisions: import 'package:http/http.dart' as http;.
- Very specific: line 33
Use package:mockito and build_runner to automatically generate mock classes for fixed scenarios and behavior verification.
- Very specific: line 35
Always use the @GenerateNiceMocks annotation (preferable to @GenerateMocks to avoid missing stub exceptions).
- Very specific: line 36
Place the annotation in the test file, passing a list of MockSpec<Type>() objects.
- Very specific: line 37
Import the generated file using the .mocks.dart extension.
- Very specific: line 44
Use when(mock.method()).thenReturn(value) for synchronous methods.
- Very specific: line 45
CRITICAL: Always use thenAnswer((_) async => value) for methods returning a Future or Stream.
- Very specific: line 47
Use verify(mock.method()).called(1) to check exact invocation counts.
- Very specific: line 48
Use argument matchers like any, anyNamed, or captureAny for flexible verification.
- Distinctive: line 52
Use the following checklist to implement and verify mocked unit tests.
- Very specific: line 67
If tests fail or build_runner encounters errors:
- Distinctive: line 69
Review errors: Check for missing stubs, mismatched argument matchers, or syntax errors in the generated files.
- Very specific: line 71
If a mock method throws an unexpected null error, ensure you used @GenerateNiceMocks.
- Very specific: line 72
If an async stub throws an ArgumentError, change thenReturn to thenAnswer.
- Very specific: line 73
If build_runner fails, ensure the .mocks.dart import matches the file name exactly.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Testing and Mocking Dart Applications
Contents
- Structuring Code for Testability
- Managing Dependencies
- Generating Mocks
- Implementing Unit Tests
- Workflow: Creating and Running Mocked Tests
- 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
Uriobjects usingUri.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) usingdart 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
@GenerateNiceMocksannotation (preferable to@GenerateMocksto 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.dartextension. - Execute
build_runnerto 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 aFutureorStream. Never usethenReturnfor asynchronous returns.
- Use
- 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, orcaptureAnyfor flexible verification.
- Use
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
partorimportdirective for the generated.mocks.dartfile. - 5. Run
dart run build_runner buildto generate the mock classes. - 6. Write the test cases using
group()andtest(). - 7. Stub required behaviors using
when(). - 8. Execute the target method.
- 9. Verify interactions using
verify()and assert outcomes usingexpect(). - 10. Run the test suite using
dart test.
Feedback Loop: Test Failures
If tests fail or build_runner encounters errors:
- Run validator: Execute
dart testordart run build_runner build. - Review errors: Check for missing stubs, mismatched argument matchers, or syntax errors in the generated files.
- Fix:
- If a mock method throws an unexpected null error, ensure you used
@GenerateNiceMocks. - If an async stub throws an
ArgumentError, changethenReturntothenAnswer. - If
build_runnerfails, ensure the.mocks.dartimport matches the file name exactly.
- If a mock method throws an unexpected null error, ensure you used
- Repeat until all tests pass.
Examples
High-Fidelity Mocking and Testing Example
1. System Under Test (lib/api_service.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)
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 exception if the http call completes with an error', () {
// Arrange
when(mockHttpClient.get(any)).thenAnswer(
(_) async => http.Response('Not Found', 404),
);
// Act & Assert
expect(
apiService.fetchData('https://api.example.com/data'),
throwsException,
);
});
});
}Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

