[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BV52Y82FWZ52XZKQMJQMBR":3,"skill-same:01M7BV52Y82FWZ52XZKQMJQMBR":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":31,"ownerHtmlUrl":32,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":33,"install":34,"resources":47},"01M7BV52Y82FWZ52XZKQMJQMBR","dart-generate-test-mocks",null,"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.","nguyenhungtran18\u002Fskill-and-tool-tracker","nguyenhungtran18","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F297063550?v=4","01M7BV0BFPRRFP84F2ME0FYZ9D","01M7BV0BG83FA5P22NJV0GR0A5",1,"MIT","https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker\u002Fblob\u002Fmain\u002Fskills\u002Fdart-generate-test-mocks\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: dart-generate-test-mocks\ndescription: 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.\nmetadata:\n  model: models\u002Fgemini-3.1-pro-preview\n  last_modified: Fri, 24 Apr 2026 15:13:58 GMT\n---\n# Testing and Mocking Dart Applications\n\n## Contents\n- [Structuring Code for Testability](#structuring-code-for-testability)\n- [Managing Dependencies](#managing-dependencies)\n- [Generating Mocks](#generating-mocks)\n- [Implementing Unit Tests](#implementing-unit-tests)\n- [Workflow: Creating and Running Mocked Tests](#workflow-creating-and-running-mocked-tests)\n- [Examples](#examples)\n\n## Structuring Code for Testability\nDesign 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.\n\n- Inject external services (e.g., `http.Client`) through class constructors.\n- Represent URLs strictly as `Uri` objects using `Uri.parse(string)`.\n- Utilize Dart's object-oriented features (classes, mixins) to define clear interfaces for external interactions.\n\n## Managing Dependencies\nConfigure the `pubspec.yaml` file with the necessary testing and code generation packages.\n\n- Add runtime dependencies (e.g., `package:http`) using `dart pub add http`.\n- Add testing dependencies using `dart pub add dev:test dev:mockito dev:build_runner`.\n- Import HTTP libraries with a prefix to avoid namespace collisions: `import 'package:http\u002Fhttp.dart' as http;`.\n\n## Generating Mocks\nUse `package:mockito` and `build_runner` to automatically generate mock classes for fixed scenarios and behavior verification.\n\n- Always use the `@GenerateNiceMocks` annotation (preferable to `@GenerateMocks` to avoid missing stub exceptions).\n- Place the annotation in the test file, passing a list of `MockSpec\u003CType>()` objects.\n- Import the generated file using the `.mocks.dart` extension.\n- Execute `build_runner` to generate the mock files: `dart run build_runner build`.\n\n## Implementing Unit Tests\nIsolate the system under test using the generated mock objects. Use `package:test` to structure the test suite.\n\n- **Stubbing:** Configure mock behavior before interacting with the system under test.\n  - Use `when(mock.method()).thenReturn(value)` for synchronous methods.\n  - **CRITICAL:** Always use `thenAnswer((_) async => value)` for methods returning a `Future` or `Stream`. Never use `thenReturn` for asynchronous returns.\n- **Verification:** Assert that the system under test interacted with the mock object correctly.\n  - Use `verify(mock.method()).called(1)` to check exact invocation counts.\n  - Use argument matchers like `any`, `anyNamed`, or `captureAny` for flexible verification.\n\n## Workflow: Creating and Running Mocked Tests\n\nUse the following checklist to implement and verify mocked unit tests.\n\n### Task Progress\n- [ ] 1. Identify the external dependency to mock (e.g., `http.Client`).\n- [ ] 2. Inject the dependency into the target class constructor.\n- [ ] 3. Create a test file (e.g., `target_test.dart`) and add `@GenerateNiceMocks([MockSpec\u003CDependency>()])`.\n- [ ] 4. Add the `part` or `import` directive for the generated `.mocks.dart` file.\n- [ ] 5. Run `dart run build_runner build` to generate the mock classes.\n- [ ] 6. Write the test cases using `group()` and `test()`.\n- [ ] 7. Stub required behaviors using `when()`.\n- [ ] 8. Execute the target method.\n- [ ] 9. Verify interactions using `verify()` and assert outcomes using `expect()`.\n- [ ] 10. Run the test suite using `dart test`.\n\n### Feedback Loop: Test Failures\nIf tests fail or `build_runner` encounters errors:\n1. **Run validator:** Execute `dart test` or `dart run build_runner build`.\n2. **Review errors:** Check for missing stubs, mismatched argument matchers, or syntax errors in the generated files.\n3. **Fix:**\n   - If a mock method throws an unexpected null error, ensure you used `@GenerateNiceMocks`.\n   - If an async stub throws an `ArgumentError`, change `thenReturn` to `thenAnswer`.\n   - If `build_runner` fails, ensure the `.mocks.dart` import matches the file name exactly.\n4. Repeat until all tests pass.\n\n## Examples\n\n### High-Fidelity Mocking and Testing Example\n\n**1. System Under Test (`lib\u002Fapi_service.dart`)**\n```dart\nimport 'dart:convert';\nimport 'package:http\u002Fhttp.dart' as http;\n\nclass ApiService {\n  final http.Client client;\n\n  ApiService(this.client);\n\n  Future\u003CString> fetchData(String urlString) async {\n    final uri = Uri.parse(urlString);\n    final response = await client.get(uri);\n\n    if (response.statusCode == 200) {\n      return jsonDecode(response.body)['data'];\n    } else {\n      throw Exception('Failed to load data');\n    }\n  }\n}\n```\n\n**2. Test Implementation (`test\u002Fapi_service_test.dart`)**\n```dart\nimport 'package:test\u002Ftest.dart';\nimport 'package:mockito\u002Fannotations.dart';\nimport 'package:mockito\u002Fmockito.dart';\nimport 'package:http\u002Fhttp.dart' as http;\nimport 'package:my_app\u002Fapi_service.dart';\n\n\u002F\u002F Generate the mock class for http.Client\n@GenerateNiceMocks([MockSpec\u003Chttp.Client>()])\nimport 'api_service_test.mocks.dart';\n\nvoid main() {\n  group('ApiService', () {\n    late ApiService apiService;\n    late MockClient mockHttpClient;\n\n    setUp(() {\n      mockHttpClient = MockClient();\n      apiService = ApiService(mockHttpClient);\n    });\n\n    test('returns data if the http call completes successfully', () async {\n      \u002F\u002F Arrange: Stub the async HTTP GET request using thenAnswer\n      when(mockHttpClient.get(any)).thenAnswer(\n        (_) async => http.Response('{\"data\": \"Success\"}', 200),\n      );\n\n      \u002F\u002F Act\n      final result = await apiService.fetchData('https:\u002F\u002Fapi.example.com\u002Fdata');\n\n      \u002F\u002F Assert\n      expect(result, 'Success');\n\n      \u002F\u002F Verify the mock was called with the correct Uri\n      verify(mockHttpClient.get(Uri.parse('https:\u002F\u002Fapi.example.com\u002Fdata'))).called(1);\n    });\n\n    test('throws an exception if the http call completes with an error', () {\n      \u002F\u002F Arrange\n      when(mockHttpClient.get(any)).thenAnswer(\n        (_) async => http.Response('Not Found', 404),\n      );\n\n      \u002F\u002F Act & Assert\n      expect(\n        apiService.fetchData('https:\u002F\u002Fapi.example.com\u002Fdata'),\n        throwsException,\n      );\n    });\n  });\n}\n```\n","# Testing and Mocking Dart Applications\n\n## Contents\n- [Structuring Code for Testability](#structuring-code-for-testability)\n- [Managing Dependencies](#managing-dependencies)\n- [Generating Mocks](#generating-mocks)\n- [Implementing Unit Tests](#implementing-unit-tests)\n- [Workflow: Creating and Running Mocked Tests](#workflow-creating-and-running-mocked-tests)\n- [Examples](#examples)\n\n## Structuring Code for Testability\nDesign 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.\n\n- Inject external services (e.g., `http.Client`) through class constructors.\n- Represent URLs strictly as `Uri` objects using `Uri.parse(string)`.\n- Utilize Dart's object-oriented features (classes, mixins) to define clear interfaces for external interactions.\n\n## Managing Dependencies\nConfigure the `pubspec.yaml` file with the necessary testing and code generation packages.\n\n- Add runtime dependencies (e.g., `package:http`) using `dart pub add http`.\n- Add testing dependencies using `dart pub add dev:test dev:mockito dev:build_runner`.\n- Import HTTP libraries with a prefix to avoid namespace collisions: `import 'package:http\u002Fhttp.dart' as http;`.\n\n## Generating Mocks\nUse `package:mockito` and `build_runner` to automatically generate mock classes for fixed scenarios and behavior verification.\n\n- Always use the `@GenerateNiceMocks` annotation (preferable to `@GenerateMocks` to avoid missing stub exceptions).\n- Place the annotation in the test file, passing a list of `MockSpec\u003CType>()` objects.\n- Import the generated file using the `.mocks.dart` extension.\n- Execute `build_runner` to generate the mock files: `dart run build_runner build`.\n\n## Implementing Unit Tests\nIsolate the system under test using the generated mock objects. Use `package:test` to structure the test suite.\n\n- **Stubbing:** Configure mock behavior before interacting with the system under test.\n  - Use `when(mock.method()).thenReturn(value)` for synchronous methods.\n  - **CRITICAL:** Always use `thenAnswer((_) async => value)` for methods returning a `Future` or `Stream`. Never use `thenReturn` for asynchronous returns.\n- **Verification:** Assert that the system under test interacted with the mock object correctly.\n  - Use `verify(mock.method()).called(1)` to check exact invocation counts.\n  - Use argument matchers like `any`, `anyNamed`, or `captureAny` for flexible verification.\n\n## Workflow: Creating and Running Mocked Tests\n\nUse the following checklist to implement and verify mocked unit tests.\n\n### Task Progress\n- [ ] 1. Identify the external dependency to mock (e.g., `http.Client`).\n- [ ] 2. Inject the dependency into the target class constructor.\n- [ ] 3. Create a test file (e.g., `target_test.dart`) and add `@GenerateNiceMocks([MockSpec\u003CDependency>()])`.\n- [ ] 4. Add the `part` or `import` directive for the generated `.mocks.dart` file.\n- [ ] 5. Run `dart run build_runner build` to generate the mock classes.\n- [ ] 6. Write the test cases using `group()` and `test()`.\n- [ ] 7. Stub required behaviors using `when()`.\n- [ ] 8. Execute the target method.\n- [ ] 9. Verify interactions using `verify()` and assert outcomes using `expect()`.\n- [ ] 10. Run the test suite using `dart test`.\n\n### Feedback Loop: Test Failures\nIf tests fail or `build_runner` encounters errors:\n1. **Run validator:** Execute `dart test` or `dart run build_runner build`.\n2. **Review errors:** Check for missing stubs, mismatched argument matchers, or syntax errors in the generated files.\n3. **Fix:**\n   - If a mock method throws an unexpected null error, ensure you used `@GenerateNiceMocks`.\n   - If an async stub throws an `ArgumentError`, change `thenReturn` to `thenAnswer`.\n   - If `build_runner` fails, ensure the `.mocks.dart` import matches the file name exactly.\n4. Repeat until all tests pass.\n\n## Examples\n\n### High-Fidelity Mocking and Testing Example\n\n**1. System Under Test (`lib\u002Fapi_service.dart`)**\n```dart\nimport 'dart:convert';\nimport 'package:http\u002Fhttp.dart' as http;\n\nclass ApiService {\n  final http.Client client;\n\n  ApiService(this.client);\n\n  Future\u003CString> fetchData(String urlString) async {\n    final uri = Uri.parse(urlString);\n    final response = await client.get(uri);\n\n    if (response.statusCode == 200) {\n      return jsonDecode(response.body)['data'];\n    } else {\n      throw Exception('Failed to load data');\n    }\n  }\n}\n```\n\n**2. Test Implementation (`test\u002Fapi_service_test.dart`)**\n```dart\nimport 'package:test\u002Ftest.dart';\nimport 'package:mockito\u002Fannotations.dart';\nimport 'package:mockito\u002Fmockito.dart';\nimport 'package:http\u002Fhttp.dart' as http;\nimport 'package:my_app\u002Fapi_service.dart';\n\n\u002F\u002F Generate the mock class for http.Client\n@GenerateNiceMocks([MockSpec\u003Chttp.Client>()])\nimport 'api_service_test.mocks.dart';\n\nvoid main() {\n  group('ApiService', () {\n    late ApiService apiService;\n    late MockClient mockHttpClient;\n\n    setUp(() {\n      mockHttpClient = MockClient();\n      apiService = ApiService(mockHttpClient);\n    });\n\n    test('returns data if the http call completes successfully', () async {\n      \u002F\u002F Arrange: Stub the async HTTP GET request using thenAnswer\n      when(mockHttpClient.get(any)).thenAnswer(\n        (_) async => http.Response('{\"data\": \"Success\"}', 200),\n      );\n\n      \u002F\u002F Act\n      final result = await apiService.fetchData('https:\u002F\u002Fapi.example.com\u002Fdata');\n\n      \u002F\u002F Assert\n      expect(result, 'Success');\n\n      \u002F\u002F Verify the mock was called with the correct Uri\n      verify(mockHttpClient.get(Uri.parse('https:\u002F\u002Fapi.example.com\u002Fdata'))).called(1);\n    });\n\n    test('throws an exception if the http call completes with an error', () {\n      \u002F\u002F Arrange\n      when(mockHttpClient.get(any)).thenAnswer(\n        (_) async => http.Response('Not Found', 404),\n      );\n\n      \u002F\u002F Act & Assert\n      expect(\n        apiService.fetchData('https:\u002F\u002Fapi.example.com\u002Fdata'),\n        throwsException,\n      );\n    });\n  });\n}\n```\n",{"name":5,"metadata":23,"description":7},{"model":24,"last_modified":25},"models\u002Fgemini-3.1-pro-preview","Fri, 24 Apr 2026 15:13:58 GMT","main","900ea3c9eb045fd5b0317dc1103777ecf3ea4aeb","skills\u002Fdart-generate-test-mocks",0,"https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker","https:\u002F\u002Fnguyenhungtran18.github.io\u002Fskill-and-tool-tracker\u002F","https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18","2026-08-31 18:36:09",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add nguyenhungtran18\u002Fskill-and-tool-tracker --skill dart-generate-test-mocks",{"tool":40,"command":41},"bunx","bunx skills add nguyenhungtran18\u002Fskill-and-tool-tracker --skill dart-generate-test-mocks",{"tool":43,"command":44},"pnpm","pnpm dlx skills add nguyenhungtran18\u002Fskill-and-tool-tracker --skill dart-generate-test-mocks","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker\u002Fblob\u002Fmain\u002Fskills\u002Fdart-generate-test-mocks\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7BVP4P83TK60JZ4P8RP9VP7","xcode-project-setup","Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).","https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker\u002Fblob\u002Fmain\u002Fskills\u002Fxcode_project_setup\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":18},"01M7BVP01K4CSJJ8G90FT8S2D5","writing-skills","Use when creating new skills, editing existing skills, or verifying skills work before deployment","https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-skills\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":18},"01M7BVNY22GXD871GYTSH599F1","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-plans\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":18},"01M7BVNQWF24RNKA8A4KM2HJ3T","workflow-skill-creator","Distills a completed user workflow or interaction into a reusable agent skill. Use when the user asks to turn their workflow, interaction, or multi-step process into a skill, or when they say \"make this a skill\", \"create a skill from what we just did\", \"package this workflow\" or similar. Do not use for creating skills from scratch without an existing workflow (use a generic skill-creator for that).","https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker\u002Fblob\u002Fmain\u002Fskills\u002Fworkflow_skill_creator\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":18},"01M7BVNNY67XPCQAQHY3FBKDGC","verify-and-stop","Prove existing work meets acceptance conditions without expanding scope. Use for validation-only tasks, completion checks, focused gate runs, and last-mile proof.","https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker\u002Fblob\u002Fmain\u002Fskills\u002Fverify-and-stop\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":18},"01M7BVNKB4Z7SZT85B73ZZ90Y6","verification-before-completion","Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always","https:\u002F\u002Fgithub.com\u002Fnguyenhungtran18\u002Fskill-and-tool-tracker\u002Fblob\u002Fmain\u002Fskills\u002Fverification-before-completion\u002FSKILL.md",[],[]]