單元測試簡介
如何編寫單元測試。
當你新增更多功能或更改現有功能時,如何確保你的應用能繼續正常工作?透過編寫測試。
單元測試對於驗證單個函式、方法或類的行為非常有用。test 包提供了編寫單元測試的核心框架,而 flutter_test 包則提供了用於測試 Widget 的額外工具。
本指南透過以下步驟演示了 test 包提供的核心功能
- 新增
test或flutter_test依賴。 - 建立測試檔案。
- 建立待測試類。
- 為我們的類編寫
test。 - 將多個測試組合在
group中。 - 執行測試。
有關 test 包的更多資訊,請參閱 test 包文件。
1. 新增測試依賴
#test 包提供了在 Dart 中編寫測試的核心功能。在編寫供 Web、伺服器和 Flutter 應用使用的包時,這是最佳方案。
要將 test 包新增為開發依賴,請執行 flutter pub add
flutter pub add dev:test
2. 建立測試檔案
#在本示例中,建立兩個檔案:counter.dart 和 counter_test.dart。
counter.dart 檔案包含你想要測試的類,位於 lib 資料夾中。counter_test.dart 檔案包含測試本身,位於 test 資料夾內。
通常,測試檔案應存放在 Flutter 應用或包根目錄下的 test 資料夾中。測試檔案應始終以 _test.dart 結尾,這是測試執行程式在搜尋測試時使用的約定。
完成後,資料夾結構應如下所示
counter_app/
lib/
counter.dart
test/
counter_test.dart
3. 建立待測試類
#接下來,你需要一個“單元”來測試。記住:“單元”是函式、方法或類的別名。在此示例中,在 lib/counter.dart 檔案中建立一個 Counter 類。它負責對從 0 開始的 value 進行遞增和遞減操作。
class Counter {
int value = 0;
void increment() => value++;
void decrement() => value--;
}
注意: 為簡單起見,本教程不遵循“測試驅動開發”(TDD)方法。如果你更習慣那種開發風格,當然也可以採用。
4. 為我們的類編寫測試
#在 counter_test.dart 檔案中,編寫第一個單元測試。測試是使用頂層 test 函式定義的,你可以使用頂層 expect 函式來檢查結果是否正確。這兩個函式均來自 test 包。
// Import the test package and Counter class
import 'package:counter_app/counter.dart';
import 'package:test/test.dart';
void main() {
test('Counter value should be incremented', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
}
5. 將多個測試組合在 group 中
#
如果你想執行一系列相關測試,請使用 flutter_test 包的 group 函式對測試進行分類。一旦放入組中,你就可以透過一條命令對該組中的所有測試呼叫 flutter test。
import 'package:counter_app/counter.dart';
import 'package:test/test.dart';
void main() {
group('Test start, increment, decrement', () {
test('value should start at 0', () {
expect(Counter().value, 0);
});
test('value should be incremented', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
test('value should be decremented', () {
final counter = Counter();
counter.decrement();
expect(counter.value, -1);
});
});
}
6. 執行測試
#現在你已經有了帶有測試的 Counter 類,可以執行測試了。
使用 IntelliJ 或 VSCode 執行測試
#IntelliJ 和 VSCode 的 Flutter 外掛支援執行測試。這通常是編寫測試時的最佳選擇,因為它提供了最快的反饋迴圈以及設定斷點的能力。
-
IntelliJ
- 開啟
counter_test.dart檔案 - 轉到 Run > Run 'tests in counter_test.dart'。你也可以按下對應平臺的快捷鍵。
- 開啟
-
VSCode
- 開啟
counter_test.dart檔案 - 轉到 Run > Start Debugging。你也可以按下對應平臺的快捷鍵。
- 開啟
在終端中執行測試
#要從終端執行所有測試,請在專案根目錄下執行以下命令
flutter test test/counter_test.dart
要執行放入 group 中的所有測試,請在專案根目錄下執行以下命令
flutter test --plain-name "Test start, increment, decrement"
此示例使用了第 5 節中建立的 group。
要了解有關單元測試的更多資訊,請執行此命令
flutter test --help