Skip to content

Flutter 测试 ​

测试不是"写完代码再补",而是让代码可被测试本身就是好架构。前面学的 Repository、Cubit、DI 全是为了让测试容易写。

Flutter 三种测试:

类型跑在哪速度用途
Unit TestDart VM极快(毫秒)函数 / Cubit / 工具类
Widget Test内存 Flutter 引擎快(秒)单个页面 / 组件
Integration Test真机 / 模拟器慢(分钟)端到端流程

外加 Golden Test(像素对比)和 Mock(替换依赖)。


一、Unit Test:测纯逻辑 ​

test 包(Dart 自带,Flutter 也用)。

dart
// test/calculator_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/calculator.dart';

void main() {
  group('Calculator', () {
    late Calculator calc;

    setUp(() {
      calc = Calculator();          // 每个 test 前重置
    });

    test('加法', () {
      expect(calc.add(1, 2), 3);
    });

    test('除以 0 抛异常', () {
      expect(() => calc.divide(1, 0), throwsArgumentError);
    });

    test('异步计算', () async {
      final r = await calc.fetchAndAdd();
      expect(r, isPositive);
    });
  });
}

跑:flutter test test/calculator_test.dart

expect 的常用 matcher ​

dart
expect(value, equals(42));
expect(list, contains(3));
expect(list, hasLength(5));
expect(map, containsPair('key', 'value'));
expect(value, isNull);
expect(value, isNotNull);
expect(value, isA<User>());
expect(value, greaterThan(10));
expect(call, throwsA(isA<MyException>()));
expect(future, completion(equals('done')));

setUp / tearDown ​

dart
setUp(() => print('每个 test 前'));
tearDown(() => print('每个 test 后'));
setUpAll(() => print('整个 group 开始一次'));
tearDownAll(() => print('整个 group 结束一次'));

二、Mock:替换依赖 ​

测 Cubit 时不能真发网络请求,要 mock Api。两个主流库:mockito 和 mocktail。推荐 mocktail(无需代码生成)。

yaml
dev_dependencies:
  mocktail: ^1.0.4
dart
class MockApi extends Mock implements Api {}

void main() {
  test('login 成功', () async {
    final api = MockApi();
    final cubit = AuthCubit(api);

    when(() => api.login('a@b.com', '1'))
        .thenAnswer((_) async => User(id: 1, name: '张三'));

    await cubit.login('a@b.com', '1');

    verify(() => api.login('a@b.com', '1')).called(1);   // 验证调用
    expect(cubit.state, isA<AuthSuccess>());
  });
}

关键 API ​

dart
when(() => api.foo()).thenReturn(value);            // 同步
when(() => api.foo()).thenAnswer((_) async => 42);  // 异步
when(() => api.foo()).thenThrow(Exception('boom')); // 抛异常

verify(() => api.foo()).called(1);                  // 调用了 1 次
verifyNever(() => api.foo());                       // 没调用
verifyInOrder([                                     // 按顺序
  () => api.a(),
  () => api.b(),
]);

any()                                               // 匹配任意参数
captureAny()                                        // 捕获参数

mockito(老牌,需要代码生成) ​

yaml
dev_dependencies:
  mockito: ^5.4.4
  build_runner: ^2.4.9
dart
@GenerateMocks([Api])
import 'auth_test.mocks.dart';

final api = MockApi();

新项目优先 mocktail,API 更现代。


三、Widget Test:测单个组件 ​

不需要真机,在内存里跑 Flutter 引擎。

dart
testWidgets('计数器点击 +1', (WidgetTester tester) async {
  await tester.pumpWidget(const MaterialApp(home: CounterPage()));

  expect(find.text('0'), findsOneWidget);

  await tester.tap(find.byIcon(Icons.add));
  await tester.pump();                    // 触发一帧

  expect(find.text('1'), findsOneWidget);
});

find:查找 Widget ​

dart
find.text('Hello')
find.byType(ElevatedButton)
find.byIcon(Icons.add)
find.byKey(const Key('login-btn'))
find.byTooltip('设置')
find.byWidgetPredicate((w) => w is Text && w.data!.startsWith('A'))

find.descendant(
  of: find.byType(AppBar),
  matching: find.byType(Icon),
)

tester:模拟交互 ​

dart
await tester.tap(find.text('OK'));
await tester.longPress(find.byType(Card));
await tester.drag(find.byType(ListView), const Offset(0, -300));
await tester.enterText(find.byType(TextField), 'hello');
await tester.testTextInput.receiveAction(TextInputAction.done);

await tester.pump();                                // 1 帧
await tester.pump(const Duration(milliseconds: 500)); // 等 500ms
await tester.pumpAndSettle();                       // 跑到所有动画结束

matcher ​

dart
expect(find.text('a'), findsOneWidget);
expect(find.text('a'), findsNothing);
expect(find.byType(ListTile), findsNWidgets(5));
expect(find.text('a'), findsAtLeastNWidgets(1));

注入依赖(配合状态管理) ​

dart
testWidgets('显示用户名', (tester) async {
  final mockUser = MockUserCubit();
  when(() => mockUser.state).thenReturn(UserState(name: '张三'));

  await tester.pumpWidget(MaterialApp(
    home: BlocProvider<UserCubit>.value(
      value: mockUser,
      child: const UserPage(),
    ),
  ));

  expect(find.text('张三'), findsOneWidget);
});

Riverpod 类似:用 ProviderScope(overrides: [...])。


四、Golden Test:像素级对比 ​

适合"按钮、卡片"这种视觉一致性重要的组件。

dart
testWidgets('卡片样式', (tester) async {
  await tester.pumpWidget(const MaterialApp(home: MyCard()));

  await expectLater(
    find.byType(MyCard),
    matchesGoldenFile('goldens/my_card.png'),
  );
});

第一次跑生成 .png,以后每次跑对比像素。

bash
flutter test --update-goldens   # 重新生成基准
flutter test                    # 比对

注意 ​

  • 跨平台像素差异:macOS 和 Linux 字体渲染不同,基准图最好在 CI 同环境生成
  • 字体加载:测试默认用占位字体,真实字体要 loadAppFonts() 加载
dart
// flutter_test 工具包
import 'package:flutter_test/flutter_test.dart';

await loadAppFonts();   // 加载真实字体

第三方包 golden_toolkit(虽然停更但好用)提供更稳定的方案,或新一些的 alchemist。


五、Bloc / Riverpod 专用测试 ​

bloc_test ​

yaml
dev_dependencies:
  bloc_test: ^9.1.7
dart
blocTest<AuthCubit, AuthState>(
  '登录成功 emit Loading → Success',
  build: () {
    final api = MockApi();
    when(() => api.login(any(), any())).thenAnswer((_) async => mockUser);
    return AuthCubit(api);
  },
  act: (cubit) => cubit.login('a@b.com', '1'),
  expect: () => [AuthLoading(), isA<AuthSuccess>()],
);

声明式描述输入 / 输出状态序列,比手写测试简洁。

Riverpod 测试 ​

dart
test('userProvider', () async {
  final container = ProviderContainer(
    overrides: [
      apiProvider.overrideWithValue(MockApi()),
    ],
  );
  addTearDown(container.dispose);

  final user = await container.read(userProvider.future);
  expect(user.name, isNotNull);
});

六、Integration Test:端到端 ​

yaml
dev_dependencies:
  integration_test:
    sdk: flutter

integration_test/app_test.dart:

dart
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main.dart' as app;

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('登录到首页流程', (tester) async {
    app.main();
    await tester.pumpAndSettle();

    await tester.enterText(find.byKey(const Key('email')), 'a@b.com');
    await tester.enterText(find.byKey(const Key('pwd')), '123');
    await tester.tap(find.text('登录'));
    await tester.pumpAndSettle();

    expect(find.text('欢迎'), findsOneWidget);
  });
}

跑:

bash
flutter test integration_test/app_test.dart

或在真机:

bash
flutter test integration_test/app_test.dart -d <device-id>

CI 上可用 Firebase Test Lab、BrowserStack 跑真机矩阵。


七、覆盖率 ​

bash
flutter test --coverage
genhtml coverage/lcov.info -o coverage/html
open coverage/html/index.html

会生成 coverage/lcov.info,可以喂给 codecov.io。

别迷信 100%。重点测:

  • 业务逻辑(Cubit、UseCase)
  • 关键工具(日期处理、价格计算)
  • 复杂 Widget(表单验证)

UI 微调、纯展示组件不必强测。


八、CI 集成 ​

GitHub Actions:

yaml
- run: flutter pub get
- run: flutter analyze
- run: flutter test --coverage
- uses: codecov/codecov-action@v4
  with:
    file: coverage/lcov.info

每次 PR 自动跑,挂了不能合。


九、典型测试结构 ​

test/
├── unit/
│   ├── cubit/
│   ├── usecase/
│   └── util/
├── widget/
│   ├── pages/
│   └── components/
├── golden/
└── helpers/
    ├── mock_api.dart
    └── pump_app.dart    ← 通用包装

pump_app.dart:

dart
Future<void> pumpApp(WidgetTester tester, Widget widget,
    {List<Override> overrides = const []}) {
  return tester.pumpWidget(
    ProviderScope(
      overrides: overrides,
      child: MaterialApp(
        localizationsDelegates: AppLocalizations.localizationsDelegates,
        supportedLocales: AppLocalizations.supportedLocales,
        home: widget,
      ),
    ),
  );
}

测试里直接 await pumpApp(tester, MyPage()),省去重复包装。


十、常见坑 ​

1. 异步代码忘了 await pump ​

dart
await tester.tap(find.text('刷新'));
expect(find.text('新数据'), findsOneWidget);   // ❌ 异步还没完

→ await tester.pumpAndSettle() 等所有动画/Future 完成。

2. Provider / Bloc 没注入 ​

dart
await tester.pumpWidget(MyPage());   // ❌ 没包 Provider

→ 抛 ProviderNotFoundException。测试也要把依赖树搭起来。

3. mock 没 stub ​

dart
when(() => api.foo()).thenAnswer((_) async => 42);
api.bar();   // ❌ 没 stub bar,默认抛异常

mocktail 默认对未 stub 的方法返回 null/抛异常。要么 stub,要么用 registerFallbackValue 注册参数类型。

4. SharedPreferences 在测试里 ​

dart
SharedPreferences.setMockInitialValues({'token': 'abc'});
final prefs = await SharedPreferences.getInstance();   // ✅ 用 mock 值

5. find.text 找不到 ​

文字可能在 RichText 里,find.text 只匹配 plain Text。用:

dart
find.textContaining('hello');
find.byWidgetPredicate((w) => w is RichText && ...);

十一、调试技巧 ​

dart
debugDumpApp();                    // 打印 Widget 树
debugDumpRenderTree();             // 打印 Render 树

// 测试里看屏幕
tester.binding.takeException();    // 拿到测试期间的异常

加 --start-paused + IDE 附加调试,可以打断点。


十二、什么时候写测试? ​

情况测?
业务逻辑(Cubit / UseCase)✅ 必须
数据转换、价格计算、日期✅ 必须
Repository 接口实现✅ 推荐
关键页面流程(登录、下单)✅ Widget Test
UI 微调❌ 没必要
第三方 SDK 包装✅ 简单测
简单展示组件❌ 看价值
端到端关键路径✅ Integration

十三、和已学知识的串联 ​

  • 因为有 Repository(13 / 14):测 Cubit 时 mock Repo 就行,不碰真实网络
  • 因为有 DI(11):测试时一行 override 就替换实现
  • Bloc / Riverpod 状态管理(09 / 10)天然好测,手动 setState 就难
  • Pigeon(16)生成的接口直接 mock,测试不依赖原生
  • 性能测试(18)用 tester.binding.collectAllElementsFrom 等 API

十四、心智模型 ​

unit test       :测函数 / 类的纯逻辑
widget test     :测一个 Widget 渲染 + 交互
integration test:测真实流程跑通
golden test     :测视觉不退化

mock = "替换依赖,让被测对象孤立"

测试三原则:

  1. 一个 test 测一件事:命名清楚说明在测什么
  2. 测行为,不测实现:用户看得到的是行为,实现可重构
  3. 测试本身要简单:测试代码出 bug 比生产代码还坑

写测试的初期会慢 30%,长期把"改动后心慌"的成本省回来。