dart-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDart Testing Automation
Dart测试自动化
Goal
目标
Analyzes Dart and Flutter codebases to architect, implement, and execute robust test suites. Generates unit, component, and integration tests utilizing and . Configures mock objects, structures test groups, and executes validation loops using or to ensure code reliability and prevent regressions.
package:testpackage:mockitodart testflutter test分析Dart和Flutter代码库,设计、实现并执行健壮的测试套件。使用和生成单元测试、组件测试和集成测试。配置模拟对象、搭建测试组结构,并使用或执行验证循环,确保代码可靠性,防止回归问题。
package:testpackage:mockitodart testflutter testDecision Logic
决策逻辑
Evaluate the target repository to determine the appropriate testing strategy:
- Project Type:
- If contains
pubspec.yaml: Usesdk: flutterand execute viaflutter_test.flutter test - If pure Dart (Server/CLI/Web): Use and execute via
package:test.dart test
- If
- 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 for widget pumping or standard component instantiation.
flutter_test - Full Application Flow: Implement Integration Tests. Use or
flutter_driverpackage.integration_test
- Isolated Logic (Functions/Classes): Implement Unit Tests. Isolate the system under test using
评估目标代码库以确定合适的测试策略:
- 项目类型:
- 如果包含
pubspec.yaml:使用sdk: flutter并通过flutter_test执行测试。flutter test - 如果是纯Dart项目(服务端/CLI/Web):使用并通过
package:test执行测试。dart test
- 如果
- 测试范围:
- 孤立逻辑(函数/类): 实现单元测试。使用隔离被测系统。
package:mockito - UI/多类交互: 实现组件/Widget测试。使用进行widget pump或标准组件实例化。
flutter_test - 完整应用流程: 实现集成测试。使用或
flutter_driver包。integration_test
- 孤立逻辑(函数/类): 实现单元测试。使用
Instructions
使用说明
-
Analyze Context and Configure Dependencies Inspect. Ensure the required testing and mocking packages are present under
pubspec.yaml.dev_dependenciesyamldev_dependencies: test: ^1.24.0 # Use flutter_test for Flutter projects mockito: ^5.4.4 build_runner: ^2.4.8 -
Generate Mock Objects Identify external dependencies (e.g., API clients, database repositories) of the system under test. Create a test file and use theannotation.
@GenerateMocksdartimport 'package:mockito/annotations.dart'; import 'package:my_app/api_client.dart'; ([ApiClient]) void main() {}Execute the build runner to generate the mock files:bashdart run build_runner build --delete-conflicting-outputsSTOP AND ASK THE USER: If you do not have execution capabilities in the current environment, provide thecommand to the user and wait for them to confirm successful generation before proceeding.build_runner -
Implement the Test Suite Write tests using thepackage. Group related tests and use descriptive names. Utilize
testwith appropriate matchers.expect()dartimport '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>()), ); }); }); } -
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 -
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.
-
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
-
分析上下文并配置依赖 检查,确保
pubspec.yaml下包含所需的测试和模拟包。dev_dependenciesyamldev_dependencies: test: ^1.24.0 # Flutter项目请使用flutter_test mockito: ^5.4.4 build_runner: ^2.4.8 -
生成模拟对象 识别被测系统的外部依赖(例如API客户端、数据库仓库),创建测试文件并使用注解。
@GenerateMocksdartimport 'package:mockito/annotations.dart'; import 'package:my_app/api_client.dart'; ([ApiClient]) void main() {}执行build runner生成模拟文件:bashdart run build_runner build --delete-conflicting-outputs停止并询问用户: 如果当前环境没有执行权限,将命令提供给用户,等待用户确认生成成功后再继续。build_runner -
实现测试套件 使用包编写测试,将相关测试分组并使用描述性名称,配合合适的匹配器使用
test。expect()dartimport '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>()), ); }); }); } -
执行测试并验证 使用对应的CLI命令运行测试套件,必要时使用参数指定特定目录或标签。bash
# 纯Dart项目使用 dart test test/data_service_test.dart # Flutter项目使用 flutter test test/data_service_test.dart -
验证-修复循环 解析测试执行的输出。
- 如果测试通过,进入下一个任务或完成实现。
- 如果测试失败,分析堆栈跟踪,识别预期值和实际值的差异,对应修改源代码或测试断言,重新运行测试直到通过。
-
配置持续集成(可选) 如果需要,生成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 package with descriptive
testandgroupnames.test - DO use with appropriate matchers (e.g.,
expect(),completion,throwsA).isA - DO run tests via (or
dart test) and use flags for specific directories or tags when applicable.flutter test - PREFER mock objects or fakes (via ) to isolate the system under test. Never make real HTTP requests or database mutations in unit tests.
package:mockito - 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 - 优先使用模拟对象或伪造对象(通过)隔离被测系统。单元测试中绝对不要发起真实HTTP请求或修改数据库。
package:mockito - 不要编写庞大的单一测试函数;严格区分准备(Arrange)、执行(Act)、断言(Assert)三个阶段。
- 不要在测试文件中留下未解决的类型提升问题;确保遵守健全空安全规则。
- 相关技能:、
dart-static-analysis。dart-code-generation