一、安裝單元測試依賴,這里選擇官方提供的test 單元測試庫。
安裝方法:
pubspec.yaml下添加
test: ^1.6.1

圖1
二、創(chuàng)建測試代碼和被測試代碼
libs/test.dart 被測試文件
class Counter {
int value = 0;
void increment() => value++;
void decrement() => value--;
}
test/testtest.dart 測試文件
// Import the test package and Counter class
import 'package:test_api/test_api.dart';
import 'package:learnta_dialer/test.dart';
void main() {
test('Counter value should be incremented', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
}
三、輸入命令開始測試
flutter pub run test /絕對路徑/項目名/test/testtest.dart

結果圖
四、后記爬坑
安裝依賴時候報錯
Because every version of flutter_test from sdk depends on test_api 0.2.4 and test >=1.6.4 depends on test_api 0.2.6, flutter_test from sdk is incompatible with test >=1.6.4.
So, because learnta_dialer depends on both test ^1.6.5 and flutter_test any from sdk, version solving failed.
解決方法: test_api 和 test 會有依賴限制,部分對應關系如下:
如果 test_api 0.2.6,則 test >=1.6.4
如果 test_api 0.2.5,則 test >=1.6.2 <1.6.4
如果 test_api 0.2.4,則 test 可以為1.6.1