dart-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dart Testing Automation

Dart测试自动化

Goal

目标

Analyzes Dart and Flutter codebases to architect, implement, and execute robust test suites. Generates unit, component, and integration tests utilizing
package:test
and
package:mockito
. Configures mock objects, structures test groups, and executes validation loops using
dart test
or
flutter test
to ensure code reliability and prevent regressions.
分析Dart和Flutter代码库,设计、实现并执行健壮的测试套件。使用
package:test
package:mockito
生成单元测试、组件测试和集成测试。配置模拟对象、搭建测试组结构,并使用
dart test
flutter test
执行验证循环,确保代码可靠性,防止回归问题。

Decision Logic

决策逻辑

Evaluate the target repository to determine the appropriate testing strategy:
  • Project Type:
    • If
      pubspec.yaml
      contains
      sdk: flutter
      : Use
      flutter_test
      and execute via
      flutter test
      .
    • If pure Dart (Server/CLI/Web): Use
      package:test
      and execute via
      dart test
      .
  • Test Scope:
    • Isolated Logic (Functions/Classes): Implement Unit Tests. Isolate the system under test using
      package:mockito
      .
    • UI/Multi-class interactions: Implement Component/Widget Tests. Use
      flutter_test
      for widget pumping or standard component instantiation.
    • Full Application Flow: Implement Integration Tests. Use
      flutter_driver
      or
      integration_test
      package.
评估目标代码库以确定合适的测试策略:
  • 项目类型:
    • 如果
      pubspec.yaml
      包含
      sdk: flutter
      :使用
      flutter_test
      并通过
      flutter test
      执行测试。
    • 如果是纯Dart项目(服务端/CLI/Web):使用
      package:test
      并通过
      dart test
      执行测试。
  • 测试范围:
    • 孤立逻辑(函数/类): 实现单元测试。使用
      package:mockito
      隔离被测系统。
    • UI/多类交互: 实现组件/Widget测试。使用
      flutter_test
      进行widget pump或标准组件实例化。
    • 完整应用流程: 实现集成测试。使用
      flutter_driver
      integration_test
      包。

Instructions

使用说明

  1. Analyze Context and Configure Dependencies Inspect
    pubspec.yaml
    . Ensure the required testing and mocking packages are present under
    dev_dependencies
    .
    yaml
    dev_dependencies:
      test: ^1.24.0 # Use flutter_test for Flutter projects
      mockito: ^5.4.4
      build_runner: ^2.4.8
  2. Generate Mock Objects Identify external dependencies (e.g., API clients, database repositories) of the system under test. Create a test file and use the
    @GenerateMocks
    annotation.
    dart
    import 'package:mockito/annotations.dart';
    import 'package:my_app/api_client.dart';
    
    ([ApiClient])
    void main() {}
    Execute the build runner to generate the mock files:
    bash
    dart run build_runner build --delete-conflicting-outputs
    STOP AND ASK THE USER: If you do not have execution capabilities in the current environment, provide the
    build_runner
    command to the user and wait for them to confirm successful generation before proceeding.
  3. Implement the Test Suite Write tests using the
    test
    package. Group related tests and use descriptive names. Utilize
    expect()
    with appropriate matchers.
    dart
    import 'package:test/test.dart';
    import 'package:mockito/mockito.dart';
    import 'package:my_app/data_service.dart';
    import 'api_client.mocks.dart'; // Generated mock file
    
    void main() {
      group('DataService -', () {
        late DataService dataService;
        late MockApiClient mockApiClient;
    
        setUp(() {
          mockApiClient = MockApiClient();
          dataService = DataService(apiClient: mockApiClient);
        });
    
        test('fetchData returns parsed data on successful API call', () async {
          // Arrange
          when(mockApiClient.get('/data')).thenAnswer((_) async => '{"status": "ok"}');
    
          // Act
          final result = await dataService.fetchData();
    
          // Assert
          expect(result, equals({'status': 'ok'}));
          verify(mockApiClient.get('/data')).called(1);
        });
    
        test('fetchData throws Exception on API failure', () async {
          // Arrange
          when(mockApiClient.get('/data')).thenThrow(Exception('Network Error'));
    
          // Act & Assert
          expect(
            () => dataService.fetchData(),
            throwsA(isA<Exception>()),
          );
        });
      });
    }
  4. Execute Tests and Validate Run the test suite using the appropriate CLI command. Use flags to target specific directories or tags if necessary.
    bash
    # For pure Dart projects
    dart test test/data_service_test.dart
    
    # For Flutter projects
    flutter test test/data_service_test.dart
  5. Validate-and-Fix Loop Parse the output of the test execution.
    • If tests pass, proceed to the next task or finalize the implementation.
    • If tests fail, analyze the stack trace, identify the mismatch between expected and actual values, modify the source code or the test assertions accordingly, and re-run the tests until they pass.
  6. Configure Continuous Integration (Optional) If requested, generate a GitHub Actions workflow to automate test execution.
    yaml
    name: Dart CI
    on: [push, pull_request]
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: dart-lang/setup-dart@v1
          - run: dart pub get
          - run: dart test
  1. 分析上下文并配置依赖 检查
    pubspec.yaml
    ,确保
    dev_dependencies
    下包含所需的测试和模拟包。
    yaml
    dev_dependencies:
      test: ^1.24.0 # Flutter项目请使用flutter_test
      mockito: ^5.4.4
      build_runner: ^2.4.8
  2. 生成模拟对象 识别被测系统的外部依赖(例如API客户端、数据库仓库),创建测试文件并使用
    @GenerateMocks
    注解。
    dart
    import 'package:mockito/annotations.dart';
    import 'package:my_app/api_client.dart';
    
    ([ApiClient])
    void main() {}
    执行build runner生成模拟文件:
    bash
    dart run build_runner build --delete-conflicting-outputs
    停止并询问用户: 如果当前环境没有执行权限,将
    build_runner
    命令提供给用户,等待用户确认生成成功后再继续。
  3. 实现测试套件 使用
    test
    包编写测试,将相关测试分组并使用描述性名称,配合合适的匹配器使用
    expect()
    dart
    import 'package:test/test.dart';
    import 'package:mockito/mockito.dart';
    import 'package:my_app/data_service.dart';
    import 'api_client.mocks.dart'; // 生成的模拟文件
    
    void main() {
      group('DataService -', () {
        late DataService dataService;
        late MockApiClient mockApiClient;
    
        setUp(() {
          mockApiClient = MockApiClient();
          dataService = DataService(apiClient: mockApiClient);
        });
    
        test('fetchData在API调用成功时返回解析后的数据', () async {
          // 准备阶段
          when(mockApiClient.get('/data')).thenAnswer((_) async => '{"status": "ok"}');
    
          // 执行阶段
          final result = await dataService.fetchData();
    
          // 断言阶段
          expect(result, equals({'status': 'ok'}));
          verify(mockApiClient.get('/data')).called(1);
        });
    
        test('fetchData在API调用失败时抛出异常', () async {
          // 准备阶段
          when(mockApiClient.get('/data')).thenThrow(Exception('Network Error'));
    
          // 执行&断言阶段
          expect(
            () => dataService.fetchData(),
            throwsA(isA<Exception>()),
          );
        });
      });
    }
  4. 执行测试并验证 使用对应的CLI命令运行测试套件,必要时使用参数指定特定目录或标签。
    bash
    # 纯Dart项目使用
    dart test test/data_service_test.dart
    
    # Flutter项目使用
    flutter test test/data_service_test.dart
  5. 验证-修复循环 解析测试执行的输出。
    • 如果测试通过,进入下一个任务或完成实现。
    • 如果测试失败,分析堆栈跟踪,识别预期值和实际值的差异,对应修改源代码或测试断言,重新运行测试直到通过。
  6. 配置持续集成(可选) 如果需要,生成GitHub Actions工作流来自动执行测试。
    yaml
    name: Dart CI
    on: [push, pull_request]
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: dart-lang/setup-dart@v1
          - run: dart pub get
          - run: dart test

Constraints

约束

  • DO write tests using the
    test
    package with descriptive
    group
    and
    test
    names.
  • DO use
    expect()
    with appropriate matchers (e.g.,
    completion
    ,
    throwsA
    ,
    isA
    ).
  • DO run tests via
    dart test
    (or
    flutter test
    ) and use flags for specific directories or tags when applicable.
  • PREFER mock objects or fakes (via
    package:mockito
    ) to isolate the system under test. Never make real HTTP requests or database mutations in unit tests.
  • DO NOT write monolithic test functions; strictly separate Arrange, Act, and Assert phases.
  • DO NOT leave unresolved type promotion failures in test files; ensure sound null safety is respected.
  • Related Skills:
    dart-static-analysis
    ,
    dart-code-generation
    .
  • 必须使用
    test
    包编写测试,
    group
    test
    命名要具备描述性。
  • 必须配合合适的匹配器(例如
    completion
    throwsA
    isA
    )使用
    expect()
  • 必须通过
    dart test
    (或
    flutter test
    )运行测试,适用时使用参数指定特定目录或标签。
  • 优先使用模拟对象或伪造对象(通过
    package:mockito
    )隔离被测系统。单元测试中绝对不要发起真实HTTP请求或修改数据库。
  • 不要编写庞大的单一测试函数;严格区分准备(Arrange)、执行(Act)、断言(Assert)三个阶段。
  • 不要在测试文件中留下未解决的类型提升问题;确保遵守健全空安全规则。
  • 相关技能:
    dart-static-analysis
    dart-code-generation