使用 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