使用 JUnit 進行單元測試

在這裡,我們有一個類 Counter 與方法 countNumbers()hasNumbers()

public class Counter {

    /* To count the numbers in the input */
    public static int countNumbers(String input) {
        int count = 0;
        for (char letter : input.toCharArray()) {
            if (Character.isDigit(letter))
                count++;
        }
        return count;
    }

    /* To check whether the input has number*/
    public static boolean hasNumber(String input) {
        return input.matches(".*\\d.*");
    }
}

要對這個類進行單元測試,我們可以使用 Junit 框架。在專案類路徑中新增 junit.jar。然後建立 Test case 類,如下所示:

import org.junit.Assert; // imports from the junit.jar
import org.junit.Test;

public class CounterTest {

    @Test // Test annotation makes this method as a test case
    public void countNumbersTest() {
        int expectedCount = 3;
        int actualCount = Counter.countNumbers("Hi 123");
        Assert.assertEquals(expectedCount, actualCount); //compares expected and actual value
    }

    @Test
    public void hasNumberTest() {
        boolean expectedValue = false;
        boolean actualValue = Counter.hasNumber("Hi there!");
        Assert.assertEquals(expectedValue, actualValue);
    }
}

在 IDE 中,你可以將此類作為 Junit testcase 執行,並在 GUI 中檢視輸出。在命令提示符下,你可以編譯並執行測試用例,如下所示:

成功測試執行的輸出應類似於:

JUnit version 4.9b2
..
Time: 0.019

OK (2 tests)

在測試失敗的情況下,它看起來更像是:

Time: 0.024
There was 1 failure:
1) CountNumbersTest(CounterTest)
java.lang.AssertionError: expected:<30> but was:<3>
... // truncated output
FAILURES!!!
Tests run: 2,  Failures: 1