运行环境:
- 单元测试:运行于内存中
- widget测试:运行于内存中
- 集成测试:运行在真机或模拟器中
-
使用
flutter_test
单元测试
import 'package:flutter_test/flutter_test.dart';
import 'package:hi_base/hi_cache.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
/// 单元测试不直接读取磁盘,读取需要模拟出来
test('adds one to input values', () async {
/// 修复 报 ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized. 的异常
TestWidgetsFlutterBinding.ensureInitialized();
/// 修复 没有引入SharedPreferences的错误
SharedPreferences.setMockInitialValues({});
await HiCache.preInit();
var key = 'testKey', value = 'hello';
HiCache.getInstance().setString(key, value);
expect(HiCache.getInstance().get(key), 'helloo');
});
}
测试结果:
package:test_api expect
package:flutter_test/src/widget_tester.dart 441:3 expect
test/hi_base_test.dart 13:5 main.<fn>
Expected: 'helloo'
Actual: 'hello'
Which: is different. Both strings start the same, but the actual value is missing the following trailing characters: o
-
使用
flutter_test
进行widget
测试
widget测试需要widget能够独立运行。
-
集成测试
- 添加测试驱动
添加依赖库:(这个库目前有问题,不支持Null Safety
)
# 集成测试
integration_test: ^1.0.2+3
项目根目录创建文件夹test_driver
,创建文件integration_test.dart
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() => integrationDriver();
- 编写测试用例
项目根目录创建文件夹integration_test
,创建文件app_test.dart
项目中要测试的按钮代码:
Padding(
padding: const EdgeInsets.symmetric(vertical: 5.0),
child: FloatingActionButton(
key: Key('Bloc Key'),
child: Center(child: Text('Bloc')),
onPressed: () {
HiNavigator.getInstance().onJumpTo(RouteStatus.testBloc);
},
),
),
``key为
Bloc Key`的按钮点击测试。
测试代码:
import 'package:flutter/material.dart';
import 'package:flutter_bilibili/main.dart' as app;
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
void main() {
/// 集成测试初始化
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('测试 widget', (WidgetTester tester) async {
/// 构建应用
app.main();
/// 捕获一帧
await tester.pumpAndSettle();
/// 获取要点击的按钮
var floatButton = find.byKey(Key('Bloc Key'));
/// 触发按钮的点击事件
await tester.press(floatButton);
/// 重新捕获一帧
await tester.pumpAndSettle();
Future.delayed(Duration(seconds: 3));
/// 测试是否正确跳转页面
expect(HiNavigator.getInstance().getCurrent()?.routeStatus, RouteStatus.testBloc);
});
}
- 运行测试用例
集成测试,要通过命令行运行
flutter driver --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart
其中: --driver
指定驱动所在路径,--target
指定测试用例所在路径
- 查看结果
目前integration_test
不支持Null Safety
,在flutter2.x
上运行报错。
网友评论