示例工程 ch09-navigation
ch09-navigation/test/navigation_test.dart
import 'package:ch09_navigation/main.dart';
import 'package:ch09_navigation/src/theme.dart';
import 'package:flutter/material.dart';
import 'package:ch09_navigation/src/profile.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:ch09_navigation/src/routes.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('路由:push / pop / 返回值', () {
testWidgets('直接 push 详情页,返回时把结果带回首页', (WidgetTester tester) async {
await tester.pumpWidget(const NavigationApp());
await tester.pumpAndSettle();
expect(find.text('路由与导航'), findsOneWidget);
await tester.tap(find.byKey(const Key('push-direct')));
await tester.pumpAndSettle();
expect(find.text('直接构造的路由'), findsOneWidget);
await tester.enterText(find.byKey(const Key('detail-note')), '来自详情页的值');
await tester.tap(find.byKey(const Key('pop-with-result')));
await tester.pumpAndSettle();
// 回到首页,并且拿到了返回值
expect(find.text('路由与导航'), findsOneWidget);
expect(find.byKey(const Key('last-result')), findsOneWidget);
expect(find.text('上次返回值:来自详情页的值'), findsOneWidget);
});
testWidgets('具名路由 + 强类型参数', (WidgetTester tester) async {
await tester.pumpWidget(const NavigationApp());
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('push-named')));
await tester.pumpAndSettle();
expect(find.text('具名路由 + 参数'), findsOneWidget);
// 路由名来自 MaterialPageRoute 的 settings
expect(find.text('当前路由: /detail'), findsOneWidget);
await tester.tap(find.byKey(const Key('pop-empty')));
await tester.pumpAndSettle();
expect(find.text('上次返回值:(无返回值)'), findsOneWidget);
});
testWidgets('routes 表里的具名路由', (WidgetTester tester) async {
await tester.pumpWidget(const NavigationApp());
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('push-about')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('about-text')), findsOneWidget);
// AppBar 的返回按钮
await tester.tap(find.byType(BackButton));
await tester.pumpAndSettle();
expect(find.text('路由与导航'), findsOneWidget);
});
testWidgets('未知路由走 onUnknownRoute', (WidgetTester tester) async {
await tester.pumpWidget(const NavigationApp());
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('push-unknown')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('unknown-text')), findsOneWidget);
expect(find.text('没有这个路由: /nope'), findsOneWidget);
});
});
group('PopScope:拦截返回', () {
testWidgets('有未保存内容:maybePop 被拦下并弹确认框,"放弃"后才出栈', (WidgetTester tester) async {
await tester.pumpWidget(const NavigationApp());
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('push-direct')));
await tester.pumpAndSettle();
// 详情页预填了备注 → 一进来就是"脏"的
final BuildContext pageContext = tester.element(find.byKey(const Key('detail-note')));
expect(ModalRoute.of(pageContext)!.popDisposition, RoutePopDisposition.doNotPop);
// 模拟系统返回(桌面端 Alt+←、Android 返回键都走 maybePop 这条路径)
final bool handled = await Navigator.of(pageContext).maybePop();
await tester.pumpAndSettle();
// ★ 陷阱:被拦下时 maybePop 仍然返回 true——它的语义是"这次返回请求被处理了",
// 不表示"成功出栈"。判断是否出栈要看界面/路由栈。
expect(handled, isTrue);
expect(find.text('放弃编辑?'), findsOneWidget);
expect(find.byKey(const Key('detail-note')), findsOneWidget); // 仍在详情页
await tester.tap(find.byKey(const Key('keep-editing')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('detail-note')), findsOneWidget);
// 再来一次,这次选"放弃"
await Navigator.of(tester.element(find.byKey(const Key('detail-note')))).maybePop();
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('discard')));
await tester.pumpAndSettle();
expect(find.text('路由与导航'), findsOneWidget); // 回到首页
});
testWidgets('没有未保存内容时直接返回,不拦截', (WidgetTester tester) async {
await tester.pumpWidget(const NavigationApp());
await tester.pumpAndSettle();
// 具名路由的 DetailArgs 没有预填备注 → 不脏
await tester.tap(find.byKey(const Key('push-named')));
await tester.pumpAndSettle();
final BuildContext pageContext = tester.element(find.byKey(const Key('detail-note')));
expect(ModalRoute.of(pageContext)!.popDisposition, RoutePopDisposition.pop);
await Navigator.of(pageContext).maybePop();
await tester.pumpAndSettle();
expect(find.text('放弃编辑?'), findsNothing);
expect(find.text('路由与导航'), findsOneWidget);
});
});
group('主题', () {
testWidgets('切换按钮在亮/暗之间切换,ThemeExtension 跟着变', (WidgetTester tester) async {
await tester.pumpWidget(const NavigationApp());
await tester.pumpAndSettle();
Brightness brightnessOf(WidgetTester t) =>
Theme.of(t.element(find.byType(Scaffold).first)).brightness;
expect(brightnessOf(tester), Brightness.light);
final Color lightBanner =
Theme.of(tester.element(find.byKey(const Key('brand-banner')))).extension<BrandColors>()!.banner;
await tester.tap(find.byKey(const Key('theme-toggle')));
await tester.pumpAndSettle();
expect(brightnessOf(tester), Brightness.dark);
final Color darkBanner =
Theme.of(tester.element(find.byKey(const Key('brand-banner')))).extension<BrandColors>()!.banner;
expect(darkBanner, isNot(lightBanner));
await tester.tap(find.byKey(const Key('theme-toggle')));
await tester.pumpAndSettle();
expect(brightnessOf(tester), Brightness.light);
});
testWidgets('亮/暗主题都注册了 BrandColors', (WidgetTester tester) async {
expect(lightTheme().extension<BrandColors>(), isNotNull);
expect(darkTheme().extension<BrandColors>(), isNotNull);
expect(lightTheme().brightness, Brightness.light);
expect(darkTheme().brightness, Brightness.dark);
});
});
group('资源 assets', () {
test('Profile.parse 是纯函数,可以直接用字符串测', () {
final Profile p = Profile.parse('''
{
"name": "Ada Lovelace",
"role": "Analytical Engine Programmer",
"tags": ["dart", "ffi", 42]
}
''');
expect(p.name, 'Ada Lovelace');
expect(p.role, 'Analytical Engine Programmer');
expect(p.tags, <String>['dart', 'ffi']); // 非字符串被 whereType 过滤掉
});
test('缺失字段有默认值', () {
final Profile p = Profile.parse('{}');
expect(p.name, '未知');
expect(p.role, '');
expect(p.tags, isEmpty);
});
testWidgets('注入假 loader 就能测 UI(不碰真实 assets)', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ProfileCard(
loader: () async => '{"name":"Mock","role":"Tester","tags":["x"]}',
),
),
),
);
await tester.pump(); // loader 的 Future 在微任务里完成
expect(find.text('Mock · Tester'), findsOneWidget);
expect(find.text('x'), findsOneWidget);
});
testWidgets('loader 抛错时显示错误态', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ProfileCard(loader: () async => throw StateError('文件丢失')),
),
),
);
await tester.pump();
expect(find.byKey(const Key('profile-error')), findsOneWidget);
expect(find.textContaining('文件丢失'), findsOneWidget);
});
testWidgets('真实 assets:从 rootBundle 读取并解析 profile.json', (WidgetTester tester) async {
// 资源读取是真异步 I/O,必须放在 runAsync 里用真实事件循环跑,
// 否则 Future 会被卡在测试的 fake-async 时钟里(一直是"加载中…")。
await tester.runAsync(() async {
// 用 cache: false 绕开 CachingAssetBundle 的跨测试缓存:
// 前一个用例缓存的 Future 是在已结束的 fake-async 时钟里创建的,
// 在新用例里 await 它会永远不完成(这是 flutter_test 的经典坑)。
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ProfileCard(
loader: () => rootBundle
.loadString('assets/data/profile.json', cache: false),
),
),
),
);
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump();
});
expect(find.byKey(const Key('profile-error')), findsNothing);
expect(find.text('Ada Lovelace · Analytical Engine Programmer'), findsOneWidget);
expect(find.text('dart'), findsOneWidget);
expect(find.text('ffi'), findsOneWidget);
});
});
group('整页冒烟', () {
testWidgets('首页所有演示区块都能渲染', (WidgetTester tester) async {
tester.view.physicalSize = const Size(900, 1200);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(const NavigationApp());
await tester.pumpAndSettle();
expect(find.byKey(const Key('brand-banner')), findsOneWidget);
expect(find.byKey(const Key('push-direct')), findsOneWidget);
expect(tester.takeException(), isNull);
});
});
}