示例工程 ch02-first-app
ch02-first-app/test/app_test.dart
import 'package:ch02_first_app/main.dart';
import 'package:ch02_first_app/src/home_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('第一个 Flutter App', () {
testWidgets('启动后渲染 AppBar 与所有知识卡片', (WidgetTester tester) async {
await tester.pumpWidget(const DartBookApp());
await tester.pumpAndSettle();
// Scaffold / AppBar 属于"框架提供的页面骨架",这里断言它们真的挂上了。
expect(find.byType(Scaffold), findsOneWidget);
expect(find.byType(AppBar), findsOneWidget);
expect(find.text('第一个 Flutter App'), findsOneWidget);
// 每一条 facts 都渲染成一张 Card:断言的是"数据驱动 UI"而非硬编码文本。
expect(find.byType(Card), findsNWidgets(facts.length));
expect(find.text('main() → runApp()'), findsOneWidget);
});
testWidgets('点击 FAB 弹出对话框,点"好"关闭', (WidgetTester tester) async {
await tester.pumpWidget(const DartBookApp());
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
await tester.tap(find.byKey(const Key('about-fab')));
await tester.pumpAndSettle(); // 等对话框动画播完
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.textContaining('第 2 章示例'), findsOneWidget);
await tester.tap(find.text('好'));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('窗口尺寸变化后布局不抛异常(桌面端会真的拉窗口)', (WidgetTester tester) async {
tester.view.physicalSize = const Size(420, 780);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(const DartBookApp());
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.byType(ListView), findsOneWidget);
tester.view.physicalSize = const Size(1280, 800);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
});
test('facts 常量表结构自洽', () {
expect(facts, isNotEmpty);
for (final Fact fact in facts) {
expect(fact.title, isNotEmpty);
expect(fact.body, isNotEmpty);
}
});
});
}