dart-add-unit-test

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Testing Dart and Flutter Applications

测试Dart与Flutter应用

Contents

目录

Structuring Test Files

测试文件结构

Organize test files to mirror the
lib
directory structure to maintain predictability.
  • Place all test code within the
    test
    directory at the root of the package.
  • Append
    _test.dart
    to the end of all test file names (e.g.,
    lib/src/utils.dart
    should be tested in
    test/src/utils_test.dart
    ).
  • If writing integration tests, place them in an
    integration_test
    directory at the root of the package.
组织测试文件以镜像
lib
目录结构,保持可预测性。
  • 将所有测试代码放在包根目录下的
    test
    目录中。
  • 所有测试文件名末尾添加
    _test.dart
    (例如,
    lib/src/utils.dart
    的测试文件应为
    test/src/utils_test.dart
    )。
  • 如果编写集成测试,将其放在包根目录下的
    integration_test
    目录中。

Writing Tests

编写测试

Utilize
package:test
as the standard testing library for Dart applications.
  • Import
    package:test/test.dart
    (or
    package:flutter_test/flutter_test.dart
    for Flutter).
  • Group related tests using the
    group()
    function to provide shared context.
  • Define individual test cases using the
    test()
    function.
  • Validate outcomes using the
    expect()
    function alongside matchers (e.g.,
    equals()
    ,
    isTrue
    ,
    throwsA()
    ).
  • Write asynchronous tests using standard
    async
    /
    await
    syntax. The test runner automatically waits for the
    Future
    to complete.
  • Manage test setup and teardown using
    setUp()
    and
    tearDown()
    callbacks.
  • If testing code that relies on dependency injection, use
    package:mockito
    alongside
    package:test
    to generate mock objects, configure fixed scenarios, and verify interactions.
使用
package:test
作为Dart应用的标准测试库。
  • 导入
    package:test/test.dart
    (Flutter项目则导入
    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
    dart test
    command.
  • If working on a Flutter project, execute tests using the
    flutter test
    command.
  • If running integration tests, explicitly specify the directory path, as the default runner ignores it:
    dart test integration_test
    or
    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
    test/
    directory, ensuring the
    _test.dart
    suffix.
  • 2. Import
    package:test/test.dart
    and the target library.
  • 3. Define a
    main()
    function.
  • 4. Initialize shared resources or mocks using
    setUp()
    .
  • 5. Write
    test()
    cases grouped by functionality using
    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);
    });
  });
}