agentleFS
ZAidBinAsifZAidBinAsif/flutter-ai-starter/.cursor/skills/generate-mocks/SKILL.md

generate-mocks

Skill0 starsChanged 5 months agoMITView on GitHub

Generate Mockito mocks with build_runner for Flutter/Dart tests

The file

Show its rules and text

We split this skill into the rules it gives an agent

15 rules. About 0 are common, 2 are distinctive, and 13 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.

  • 13

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

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

    line 33
  2. Very specific:

    Always use the @GenerateNiceMocks annotation (preferable to @GenerateMocks to avoid missing stub exceptions).

    line 35
  3. Very specific:

    Place the annotation in the test file, passing a list of MockSpec<Type>() objects.

    line 36
  4. Very specific:

    Import the generated file using the .mocks.dart extension.

    line 37
  5. Very specific:

    Use when(mock.method()).thenReturn(value) for synchronous methods.

    line 44
  6. Very specific:

    CRITICAL: Always use thenAnswer((_) async => value) for methods returning a Future or Stream.

    line 45
  7. Very specific:

    Use verify(mock.method()).called(1) to check exact invocation counts.

    line 47
  8. Very specific:

    Use argument matchers like any, anyNamed, or captureAny for flexible verification.

    line 48
  9. Distinctive:

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

    line 52
  10. Very specific:

    If tests fail or build_runner encounters errors:

    line 67
  11. Distinctive:

    Review errors: Check for missing stubs, mismatched argument matchers, or syntax errors in the generated files.

    line 69
  12. Very specific:

    If a mock method throws an unexpected null error, ensure you used @GenerateNiceMocks.

    line 71
  13. Very specific:

    If an async stub throws an ArgumentError, change thenReturn to thenAnswer.

    line 72
  14. Very specific:

    If build_runner fails, ensure the .mocks.dart import matches the file name exactly.

    line 73
  15. Very specific:

    Run dart run build_runner build after adding @GenerateNiceMocks.

    line 131

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 classes for constructor injection. Mock external I/O (dio, SupabaseClient) at repository/service boundaries — use fakes for repositories in ViewModel tests (see implement-tdd/mocking.md).

  • Inject Dio or SupabaseClient through constructors — not Supabase.instance
  • Repositories return Future<Result<T, Failure>>

Managing Dependencies

dart pub add dio
dart pub add dev:mockito dev:build_runner

build_runner is allowed for Mockito mocks and freezed — see architecture.mdc.

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., Dio, SupabaseClient).
  • 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

Repository test with Mockito + dio

1. Service (lib/features/items/data/services/item_api_service.dart)

class ItemApiService {
  ItemApiService(this._dio);
  final Dio _dio;

  Future<List<Map<String, dynamic>>> fetchItems() async {
    final response = await _dio.get('/items');
    return (response.data as List).cast<Map<String, dynamic>>();
  }
}

2. Test (test/features/items/data/services/item_api_service_test.dart)

import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';

@GenerateNiceMocks([MockSpec<Dio>()])
import 'item_api_service_test.mocks.dart';

void main() {
  late MockDio mockDio;
  late ItemApiService service;

  setUp(() {
    mockDio = MockDio();
    service = ItemApiService(mockDio);
  });

  test('returns items when dio responds 200', () async {
    when(mockDio.get('/items')).thenAnswer(
      (_) async => Response(
        requestOptions: RequestOptions(path: '/items'),
        statusCode: 200,
        data: [{'id': '1', 'name': 'A'}],
      ),
    );

    final result = await service.fetchItems();

    expect(result, hasLength(1));
    verify(mockDio.get('/items')).called(1);
  });
}

Run dart run build_runner build after adding @GenerateNiceMocks.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.