跳到主内容
智客 ZICQ

技能库 智客分类:Agent 工作流 dart-generate-test-mocks

Dart Generate Test Mocks

使用`package:mockito'和`built_runner'定义和生成外部依赖的模拟对象。 当单位测试依赖于复杂的外部服务如API或数据库时使用.

15435 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

使用“ package: mockito” 和“ building_runner” 定义和生成外部依赖的模拟对象 `(a). `

何时用

依赖于复杂的外部服务如API或数据库的单位测试类

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:Testing and Mocking Dart Applications、Contents、Structuring Code for Testability、Managing Dependencies、Generating Mocks、Implementing Unit Tests。 其中含规范建议的小节:分步指令、输入输出示例。

文件分析

文件分析:这是一份仅含 SKILL.md 的指令型技能,代理激活后整份正文进入上下文。

官方 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.

Testing and Mocking Dart ApplicationsContentsStructuring Code for TestabilityManaging DependenciesGenerating MocksImplementing Unit TestsWorkflow: Creating and Running Mocked TestsTask ProgressFeedback Loop: Test FailuresExamplesHigh-Fidelity Mocking and Testing Example

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
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.
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「dart-generate-test-mocks」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-c7b87b610d3ba381-%E8%BE%BE%E7%89%B9%E7%94%9F%E6%88%90%E6%B5%8B%E8%AF%95%E6%A8%A1%E6%8B%9F%E5%99%A8.html
请存为 .cursor/skills/dart-generate-test-mocks/SKILL.md 或 .claude/skills/dart-generate-test-mocks/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/dart-lang/skills' --list

npx skills add 'https://github.com/dart-lang/skills' --skill 'dart-generate-test-mocks'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- 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. metadata: model: models/gemini-3.1-pro-preview last_modified: Fri, 24 Apr 2026 15:13:58 GMT --- # 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()` 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()])`. - [ ] 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 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()]) 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, ); }); }); } ```

相关技能

Agent 工作流

Skill Creator

创造有效技能指南。 当用户想创造出新的技能(或更新现有的技能),以专业知识,工作流程,或工具集成来扩展克洛德的能力时,应该使用这种技能.

Agent 工作流

Clawdhub

使用ClawdHub CLI搜索,安装,更新并发布从taladhub.com的代理技能. 需要获取苍蝇上的新技能时使用,将安装的技能同步到最新版本或特定版本,或者发布 npm-instainddhub CLI 的新/更新的技能文件夹.

Agent 工作流

Agent Team Orchestration

管弦乐团多代理团队,任务设定周期,交接协议,审查工作流程. 使用时间: (1)建立2+特派员队伍,具有不同专业,(2)确定任务路线和生命周期(收录框_ spec_建设_审查_完成),(3)在特派员之间制定交接协议,(4)建立审查和质量关口,(5)管理特派员之间的交流和文物共享.

Agent 工作流

Superpowers

Spec-first,TDD,子代理驱动的软件开发工作流程. 当:(1)构建任何新功能或应用——触发脑暴_计划_子代理执行回路,(2)调试出一个bug或测试失败——触发系统性的根起过程,(3)用户说"让我们构建","帮助我计划","我想添加X",或"这个被打破",(4)完成一个功…