開始使用免費開始

CsvSource:數字

你再次回到第 1 章的 lastDigit(),這次已用 Math.abs() 處理負值。既然你已知道可以用 @ParameterizedTest 精簡測試,你嘗試在一次測試中涵蓋 lastDigit() 的所有結果。

請驗證此方法對正數、負數,以及尾數為 0 的整數都會回傳正確的位數。

本練習屬於課程

Java 測試入門

檢視課程

練習說明

  • 使用能將多筆輸入值帶入測試方法的標註。
  • 為測試方法加入對應的方法參數。

動手互動練習

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

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

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

class LastDigitTest {

    @ParameterizedTest
    // Use the correct annotation for a pair of integer inputs
    @____(value = {"2025, 5", "-2025, 5", "2020, 0"}) 
    // Write the corresponding argument types for the test method
    void testLastDigit(____ number, ____ expected) {
        int actual = LastDigit.lastDigit(number);

        assertEquals(expected, actual);
    }
}
編輯並執行程式碼