Eclipse IDE 集成了JUnit開源單元測試框架。如果不借助Eclipse的圖形界面工具來生成並運行我們的JUnit測試,該怎麼實現呢?
1. 首先需要在類路徑下添加JUnit-4.X jar 包。
2. 編寫需要測試的方法。
public class Calculator {
private Calculator(){}
public static int add(int x, int y) {
return x + y; // 正確
}
public static int subtract(int x,int y) {
return y - x; // 錯誤
}
public static int multiply(int x, int y) {
throw new RuntimeException(); // 拋出異常
}
public static int divide(int x, int y) {
return x / y; // divided by 0
}
public static int module(int x , int y) {
for(;;); //死循環
}
}
編寫測試類(Test Class)
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.zjut.junit.Calculator.*;
public class CalculatorTest {
@Before
public void setUp() throws Exception {
System.out.println("Before testing");
}
@After
public void tearDown() throws Exception {
System.out.println("After testing");
}
@Test
public void testAdd() {
assertEquals("add", 3, add(1, 2));
}
@Test
public void testSubtract() {
assertEquals("subtract", 3, subtract(5, 2));
}
@Test
public void testMultiply() {
assertEquals("multiply", 9, multiply(3, 3));
}
@Test(expected = ArithmeticException.class)
public void testDivide() {
divide(3, 0);
}
@Test(timeout=200)
public void testModule() {
module(1, 2);
}
}