開始使用免費開始

使用 MethodSource 的數字

和多數歷史悠久且熱門的程式語言一樣,Java 有龐大的生態系,而且達成同一件事通常有很多作法。

回想前一課的 LastDigit 練習。請用本課介紹的語法,改寫成使用 @MethodSource 的版本。

本練習屬於課程

Java 測試入門

檢視課程

練習說明

  • 使用正確的註解來建立從方法取得引數的參數化測試。
  • 將該註解指向引數提供者方法。
  • 以相同語法重複三次,建立成對的引數。

動手互動練習

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

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

class LastDigitTest {

    @ParameterizedTest
    // Add the annotation to use a method to provide arguments and point it to the arguments method
    @____("____")
    void testLastDigit(int number, int expected) {
        int actual = LastDigit.lastDigit(number);

        assertEquals(expected, actual);
    }

    private static List getArgs() {
        return List.of(
        	// Create three argument objects for the test using the same syntax
            ____.of(2025, 5),
            ____.of(-2025, 5),
            ____.of(2020, 0)
        );
    }
}
編輯並執行程式碼