skills/dart/dart-generate-test-mocks/SKILL.md
Define and generate mock objects for external dependencies using `package:mockito` and the `build_runner` code generation lifecycle for unit testing classes.
npx skillsauth add dhruvanbhalara/skills dart-generate-test-mocksInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
To write effective unit tests, structure your codebase using dependency injection. Isolate operations that interact with physical layers (like disk storage, external servers, and platform channels) so they can be replaced by mock objects at test time:
Configure your pubspec.yaml to specify the packages required for code generation and mock testing:
dev_dependencies:
dart pub add dev:test dev:mockito dev:build_runner
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
Leverage package:mockito alongside build_runner to generate mock structures automatically:
@GenerateNiceMocks annotation instead of the legacy @GenerateMocks. Nice mocks automatically return null or matching default values instead of throwing "MissingStubException" when a method is invoked without a pre-configured stub.@GenerateNiceMocks([MockSpec<YourService>()])..mocks.dart suffix (e.g. import 'service_test.mocks.dart').dart run build_runner build --delete-conflicting-outputs
Write robust mock interactions by adhering to these guidelines:
Future or a Stream, always use .thenAnswer((_) async => value). Never use .thenReturn() for asynchronous return values, as this causes runtime cast errors.verify() API to verify that specific methods were invoked. Call .called(number) to assert precise invocation counts.verifyNever() or verifyNoMoreInteractions(mock) to guarantee that no unexpected actions occurred during the test lifecycle.Follow this checklist to establish mock configurations:
test/feature_test.dart and import Mockito along with testing libraries.@GenerateNiceMocks([MockSpec<TargetService>()]) above main().feature_test.mocks.dart.dart run build_runner build in your terminal to create the mocked file.setUp callback, instantiate the generated mock class (e.g. mockService = MockTargetService()).when().expect().verify() to assert mock interactions.This example shows how to mock a remote API client to test a database synchronization service.
import 'package:test/test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:http/http.dart' as http;
// Define an abstract contract for a user repository
abstract class UserRepository {
Future<String> getUserName(int id);
}
// System Under Test consuming the repository
class UserService {
final UserRepository repository;
UserService(this.repository);
Future<String> fetchDisplayName(int id) async {
try {
final name = await repository.getUserName(id);
return 'User: $name';
} catch (_) {
return 'Unknown User';
}
}
}
// 1. Annotate to generate MockUserRepository
@GenerateNiceMocks([MockSpec<UserRepository>()])
import 'user_service_test.mocks.dart';
void main() {
group('UserService', () {
late MockUserRepository mockRepo;
late UserService userService;
setUp(() {
mockRepo = MockUserRepository();
userService = UserService(mockRepo);
});
test('returns formatted display name when repository succeeds', () async {
// 2. Arrange: Stub the async getUserName method
when(mockRepo.getUserName(42)).thenAnswer(
(_) async => 'Alice',
);
// 3. Act: Run target method
final displayName = await userService.fetchDisplayName(42);
// 4. Assert: Validate outcomes
expect(displayName, equals('User: Alice'));
// 5. Verify: Assert the repository method was invoked with correct arguments
verify(mockRepo.getUserName(42)).called(1);
});
test('returns fallback string when repository throws exception', () async {
// Arrange: Stub to throw error
when(mockRepo.getUserName(any)).thenThrow(
Exception('Connection Timeout'),
);
// Act
final displayName = await userService.fetchDisplayName(99);
// Assert
expect(displayName, equals('Unknown User'));
});
});
}
development
Perform REST API networking operations (GET, POST, PUT, DELETE) using the lightweight and robust standard `http` package, including platform configurations and background parsing models.
development
Configure internationalization and localization support using Flutter's built-in l10n system, App Resource Bundle (ARB) files, and ICU formatting syntax.
development
Create model classes with fromJson/toJson using dart:convert and Dart 3 pattern matching. Use when manually mapping JSON to classes, parsing HTTP responses, or choosing between manual and code-generated serialization.
data-ai
Diagnose and fix Flutter layout constraint violations (RenderFlex overflow, unbounded height/width, ParentData misuse). Use when encountering layout exceptions, yellow-black overflow stripes, or red error screens.