dart-generate-test-mocks
Define and generate mock objects for external dependencies using `package:mockito` and `build_runner`.
Skill by maranix
Install
Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.
npx agentmarket install skill/maranix-dart-generate-test-mocks
Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.
Get the weekly diff
The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.
About
Use cases: testing
Reviews
Write a reviewNo reviews yet. Installed it? Reviews come from verified installers only. How reviews work
Permissions
What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.
- Tools
- No tools found
- Secrets
- None asked for
- Install scripts
- None found
Network hosts it talks to 1
codeload.github.com· found in install command
Files it touches
~/.claude/skills/dart-generate-test-mocks
What's inside
- Skill 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.
- License
- MIT
- Metadata
- model: models/gemini-3.1-pro-preview · last_modified: Fri, 24 Apr 2026 15:13:58 GMT
- Instructions
- 149 lines in SKILL.md · view on GitHub
Files (1)
- SKILL.md
SKILL.md (first lines)
# 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(From maranix/skills, MIT.
More from maranix/skills
- 0.524score
dart-add-unit-test
maranix
Write and organize unit tests for functions, methods, and classes using `package:test`.
SkillBFreshness: BClaude Code +9 - 0.524score
dart-build-cli-app
maranix
Entrypoint structure, exit codes, cross-platform scripts.
SkillBFreshness: BClaude Code +9 - 0.524score
flutter-add-integration-test
maranix
Configures Flutter Driver for app interaction and converts MCP actions into permanent integration tests.
SkillBFreshness: BClaude Code +9 - 0.524score
flutter-add-widget-test
maranix
Implement a component-level test using `WidgetTester` to verify UI rendering and user interactions (tapping, scrolling, entering text).
SkillBFreshness: BClaude Code +9 - 0.524score
dart-setup-ffi-assets
maranix
Guides agents in compiling and packaging C/C++ source code into dynamic or static libraries (Code Assets) using Dart's Native Assets hook system (via…
SkillBFreshness: BClaude Code +9 - 0.524score
dart-use-ffigen
maranix
Guide agents to use `package:ffigen` to automatically generate FFI bindings instead of writing them manually.
SkillBFreshness: BClaude Code +9 - 0.524score
flutter-apply-architecture-best-practices
maranix
Architects a Flutter application using the recommended layered approach (UI, Logic, Data).
SkillBFreshness: BClaude Code +9 - 0.524score
flutter-build-responsive-layout
maranix
Use `LayoutBuilder`, `MediaQuery`, or `Expanded/Flexible` to create a layout that adapts to different screen sizes.
SkillBFreshness: BClaude Code +9 - 0.523score
dart-resolve-package-conflicts
maranix
Workflow for fixing package version conflicts.
SkillBFreshness: BClaude Code +9 - 0.521score
dart-fix-runtime-errors
maranix
Uses get_runtime_errors and lsp to fetch an active stack trace, locate the failing line, apply a fix, and verify resolution via hot_reload.
SkillBFreshness: BClaude Code +9 - 0.521score
dart-run-static-analysis
maranix
Execute `dart analyze` to identify warnings and errors, and use `dart fix --apply` to automatically resolve mechanical lint issues.
SkillBFreshness: BClaude Code +9 - 0.521score
dart-use-primary-constructors
maranix
Help users write syntactically and semantically correct primary constructors in Dart, and migrate/use the new constructor syntax, empty-body semicolon syntax…
SkillBFreshness: BClaude Code +9
Signals
- Stars
- 0
- Forks
- 0
- Open issues
- 0
- Last commit (this folder)
- Aug 13, 2026 (2 months ago)
From GitHub (fetched Oct 24, 2026).
Details
- License
- MIT
- Repository
- github.com/maranix/skills
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from maranix
- 0.524score
dart-add-unit-test
maranix
Write and organize unit tests for functions, methods, and classes using `package:test`.
SkillBFreshness: BClaude Code +9 - 0.524score
dart-build-cli-app
maranix
Entrypoint structure, exit codes, cross-platform scripts.
SkillBFreshness: BClaude Code +9 - 0.524score
flutter-add-integration-test
maranix
Configures Flutter Driver for app interaction and converts MCP actions into permanent integration tests.
SkillBFreshness: BClaude Code +9 - 0.524score
flutter-add-widget-test
maranix
Implement a component-level test using `WidgetTester` to verify UI rendering and user interactions (tapping, scrolling, entering text).
SkillBFreshness: BClaude Code +9 - 0.524score
dart-setup-ffi-assets
maranix
Guides agents in compiling and packaging C/C++ source code into dynamic or static libraries (Code Assets) using Dart's Native Assets hook system (via…
SkillBFreshness: BClaude Code +9 - 0.524score
dart-use-ffigen
maranix
Guide agents to use `package:ffigen` to automatically generate FFI bindings instead of writing them manually.
SkillBFreshness: BClaude Code +9
Cite this page
dart-generate-test-mocks skill. Agent Mart. https://agentmart.dev/skills/maranix-dart-generate-test-mocks (last updated 2026-10-24)