單元測試簡介
當您新增更多功能或變更現有功能時,如何確保您的應用程式持續正常運作?透過撰寫測試。
單元測試對於驗證單一函式、方法或類別的行為非常有用。 test
套件提供了撰寫單元測試的核心架構,而 flutter_test
套件則提供了額外的工具來測試 Widget。
本食譜示範了 test
套件提供的核心功能,使用以下步驟
- 新增
test
或flutter_test
依賴。 - 建立測試檔案。
- 建立要測試的類別。
- 為我們的類別撰寫
test
。 - 將多個測試合併為一個
group
。 - 執行測試。
有關 test 套件的更多資訊,請參閱 test 套件文件。
1. 新增測試依賴
#test
套件提供在 Dart 中撰寫測試的核心功能。這是撰寫網頁、伺服器和 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--;
}
注意:為了簡化,本教學課程不遵循「測試驅動開發」方法。如果您更喜歡那種開發風格,您可以隨時採用該方法。
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
檔案 - 前往 執行 > 執行 'tests in counter_test.dart'。您也可以按下適用於您平台的適當鍵盤快速鍵。
- 開啟
VSCode
- 開啟
counter_test.dart
檔案 - 前往 執行 > 開始偵錯。您也可以按下適用於您平台的適當鍵盤快速鍵。
- 開啟
在終端機中執行測試
#若要從終端機執行所有測試,請從專案根目錄執行以下命令
flutter test test/counter_test.dart
若要執行您放入一個 group
中的所有測試,請從專案根目錄執行以下命令
flutter test --plain-name "Test start, increment, decrement"
此範例使用在第 5 節中建立的 group
。
若要了解有關單元測試的更多資訊,您可以執行此命令
flutter test --help
除非另有說明,否則本網站上的文件反映了 Flutter 的最新穩定版本。頁面上次更新於 2024-04-04。 檢視原始碼 或 回報問題。