dart-add-unit-test
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTesting Dart and Flutter Applications
测试Dart与Flutter应用
Contents
目录
Structuring Test Files
测试文件结构
Organize test files to mirror the directory structure to maintain predictability.
lib- Place all test code within the directory at the root of the package.
test - Append to the end of all test file names (e.g.,
_test.dartshould be tested inlib/src/utils.dart).test/src/utils_test.dart - If writing integration tests, place them in an directory at the root of the package.
integration_test
组织测试文件以镜像目录结构,保持可预测性。
lib- 将所有测试代码放在包根目录下的目录中。
test - 所有测试文件名末尾添加(例如,
_test.dart的测试文件应为lib/src/utils.dart)。test/src/utils_test.dart - 如果编写集成测试,将其放在包根目录下的目录中。
integration_test
Writing Tests
编写测试
Utilize as the standard testing library for Dart applications.
package:test- Import (or
package:test/test.dartfor Flutter).package:flutter_test/flutter_test.dart - Group related tests using the function to provide shared context.
group() - Define individual test cases using the function.
test() - Validate outcomes using the function alongside matchers (e.g.,
expect(),equals(),isTrue).throwsA() - Write asynchronous tests using standard /
asyncsyntax. The test runner automatically waits for theawaitto complete.Future - Manage test setup and teardown using and
setUp()callbacks.tearDown() - If testing code that relies on dependency injection, use alongside
package:mockitoto generate mock objects, configure fixed scenarios, and verify interactions.package:test
使用作为Dart应用的标准测试库。
package:test- 导入(Flutter项目则导入
package:test/test.dart)。package:flutter_test/flutter_test.dart - 使用函数将相关测试分组,提供共享上下文。
group() - 使用函数定义单个测试用例。
test() - 结合匹配器(如、
equals()、isTrue)使用throwsA()函数验证结果。expect() - 使用标准/
async语法编写异步测试,测试运行器会自动等待await完成。Future - 使用和
setUp()回调管理测试的初始化与清理工作。tearDown() - 如果测试依赖依赖注入的代码,可结合使用
package:test生成模拟对象、配置固定场景并验证交互。package:mockito
Executing Tests
执行测试
Select the appropriate test runner based on the project type and test location.
- If working on a pure Dart project, execute tests using the command.
dart test - If working on a Flutter project, execute tests using the command.
flutter test - If running integration tests, explicitly specify the directory path, as the default runner ignores it: or
dart test integration_test.flutter test integration_test
根据项目类型和测试位置选择合适的测试运行器。
- 纯Dart项目使用命令执行测试。
dart test - Flutter项目使用命令执行测试。
flutter test - 运行集成测试时,需明确指定目录路径(默认运行器会忽略该目录):或
dart test integration_test。flutter test integration_test
Test Implementation Workflow
测试实施流程
Follow this sequential workflow when implementing new test suites. Copy the checklist to track your progress.
实施新测试套件时遵循以下顺序流程,可复制清单跟踪进度。
Task Progress
任务进度
- 1. Create the test file in the directory, ensuring the
test/suffix._test.dart - 2. Import and the target library.
package:test/test.dart - 3. Define a function.
main() - 4. Initialize shared resources or mocks using .
setUp() - 5. Write cases grouped by functionality using
test().group() - 6. Execute the test suite using the appropriate CLI command.
- 7. Feedback Loop: Run test -> Review stack trace for failures -> Fix implementation or assertions -> Re-run until passing.
- 1. 在目录创建测试文件,确保文件名带有
test/后缀。_test.dart - 2. 导入和目标库。
package:test/test.dart - 3. 定义函数。
main() - 4. 使用初始化共享资源或模拟对象。
setUp() - 5. 使用按功能分组编写
group()用例。test() - 6. 使用合适的CLI命令执行测试套件。
- 7. 反馈循环:运行测试 -> 查看失败堆栈跟踪 -> 修复实现或断言 -> 重新运行直至通过。
Examples
示例
Standard Unit Test Suite
标准单元测试套件
Demonstrates grouping, setup, synchronous, and asynchronous testing.
dart
import 'package:test/test.dart';
import 'package:my_package/calculator.dart';
void main() {
group('Calculator', () {
late Calculator calc;
setUp(() {
calc = Calculator();
});
test('adds two numbers correctly', () {
expect(calc.add(2, 3), equals(5));
});
test('handles asynchronous operations', () async {
final result = await calc.fetchRemoteValue();
expect(result, isNotNull);
expect(result, greaterThan(0));
});
});
}展示分组、初始化、同步与异步测试的用法。
dart
import 'package:test/test.dart';
import 'package:my_package/calculator.dart';
void main() {
group('Calculator', () {
late Calculator calc;
setUp(() {
calc = Calculator();
});
test('adds two numbers correctly', () {
expect(calc.add(2, 3), equals(5));
});
test('handles asynchronous operations', () async {
final result = await calc.fetchRemoteValue();
expect(result, isNotNull);
expect(result, greaterThan(0));
});
});
}Mocking with Mockito
使用Mockito进行模拟
Demonstrates configuring a mock object for dependency injection testing.
dart
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';
import 'package:mockito/annotations.dart';
import 'package:my_package/api_client.dart';
import 'package:my_package/data_service.dart';
// Generate the mock using build_runner: dart run build_runner build
([MockSpec<ApiClient>()])
import 'data_service_test.mocks.dart';
void main() {
group('DataService', () {
late MockApiClient mockApiClient;
late DataService dataService;
setUp(() {
mockApiClient = MockApiClient();
dataService = DataService(apiClient: mockApiClient);
});
test('returns parsed data on successful API call', () async {
// Configure the mock
when(mockApiClient.get('/data')).thenAnswer((_) async => '{"id": 1}');
// Execute the system under test
final result = await dataService.fetchData();
// Verify outcomes and interactions
expect(result.id, equals(1));
verify(mockApiClient.get('/data')).called(1);
});
});
}展示为依赖注入测试配置模拟对象的方法。
dart
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';
import 'package:mockito/annotations.dart';
import 'package:my_package/api_client.dart';
import 'package:my_package/data_service.dart';
// Generate the mock using build_runner: dart run build_runner build
([MockSpec<ApiClient>()])
import 'data_service_test.mocks.dart';
void main() {
group('DataService', () {
late MockApiClient mockApiClient;
late DataService dataService;
setUp(() {
mockApiClient = MockApiClient();
dataService = DataService(apiClient: mockApiClient);
});
test('returns parsed data on successful API call', () async {
// Configure the mock
when(mockApiClient.get('/data')).thenAnswer((_) async => '{"id": 1}');
// Execute the system under test
final result = await dataService.fetchData();
// Verify outcomes and interactions
expect(result.id, equals(1));
verify(mockApiClient.get('/data')).called(1);
});
});
}