Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

dart-generate-test-mocksdart 生成测试模拟

Agent Skill

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

总安装

1,374

周安装

59

GitHub Stars

61

下载量

481
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:dart-generate-test-mocks(dart 生成测试模拟)
来源仓库:https://github.com/dart-lang/skills
仓库路径:skills/dart-generate-test-mocks
安装命令:
npx skills add https://github.com/dart-lang/skills --skill dart-generate-test-mocks
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

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

简介

dart-generate-test-mocks 辅助生成单元测试所需的模拟对象,提升测试覆盖率和可维护性。

  • 适用于需要为 Dart 类注入依赖、隔离外部服务(如 API 客户端)的测试场景。
  • 支持基于构造函数注入设计,自动生成 mock 实现以替代真实数据库或网络调用。
  • 使用前请确认项目是否采用标准测试框架(如 package:test),并检查 pubspec.yaml 中相关依赖。
  • 生成的模拟代码仅用于测试环境,请勿将其混入生产逻辑以免引发运行时错误。

SKILL.md

Testing and Mocking Dart Applications

Contents

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.

  1. Repeat until all tests pass.

Examples

High-Fidelity Mocking and Testing Example

1. System Under Test (lib/api_service.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)

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(
        (_) 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,
      );
    });
  });
}

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.23%
按下载量换算169

Claude

28.12%
按下载量换算135

Cursor

18.3%
按下载量换算88

Gemini CLI

9.64%
按下载量换算46

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills