開始使用免費開始

數字的位數測試失敗

現在你已經寫出一個成功的測試,接著請寫一個在遇到邊界情況出現非預期行為時會失敗的測試。

軟體工程師常會刻意撰寫會失敗的測試,以證明程式中確實存在錯誤。

必要的 JUnit 套件已替你匯入。

本練習屬於課程

Java 測試入門

檢視課程

練習說明

  • 輸入正確的註解,讓 JUnit 能執行此測試。
  • 呼叫要測試的方法。
  • 使用正確的 JUnit 斷言來檢查預期行為——讓測試在不符合預期時失敗。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class LastDigitWithTests {
    public static void main(String[] args) {
        launchTestsAndPrint(LastDigitTest.class);
    }
}

class LastDigit {
    public static int lastDigit(int a) {
        return a % 10;
    }
}

class LastDigitTest {
    // Use the correct annotation to mark this as a JUnit test
    @____
    void testLastDigit() {
        int number = -2025;
        int expected = 5;

        // Call the method under test
        int actual = LastDigit.____(____);

        // Use the correct JUnit assertion for the scenario
        ____(expected, actual);
    }
}
編輯並執行程式碼