開始使用免費開始

套用 TDD 來反轉數字

你已經看過測試驅動開發(TDD)— 現在就來實作吧!想一個將 int 反轉的簡單方法。以 TDD 的思維來看,你首先需要做的是寫測試。專注在方法的行為(輸入與輸出),而不是它的實作。這會訓練你把專案需求放在第一優先。

在下方的程式碼片段中,完成測試:填入預期輸出、取得方法實際輸出的運算式,以及 assertEquals() 陳述式中的運算式。

本練習屬於課程

Java 測試入門

檢視課程

練習說明

  • 輸入該數字反轉後的正確值。
  • 呼叫 IntReverserreverse() 方法以取得實際值。
  • JUnit 對 expectedactual 的順序有特定要求。請將它們依序填入 assertEquals()

動手互動練習

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

public class IntReverser {
    
    public static int reverse(int input) {
        return 0;
    }

    public static class IntReverserTest {
    
        @Test
        public void testReverse_reversesNumber() {
            int input = 1234;
            // Write down the expected return value
            int expected = ____;

			// Call the reverse() method to obtain its actual return value
            int actual = IntReverser.____(____);

			// Write the arguments for the assert statement in the correct order
            assertEquals(____, ____);
        }
    }

    public static void main(String[] args) {
		launchTestsAndPrint(IntReverserTest.class);
    }
}
編輯並執行程式碼