首先导入junit的jar包,
写一个类:
/**
* java做加减乘除
* @author young
*
*/
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int minus(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) throws Exception {
if (0 == b) {
throw new Exception("除数不能为零");
}
return a / b;
}
}
再新建一个JUnit测试类:
import junit.framework.TestCase;
/**
* JUnit单元测试
* @author young
*
*/
public class CalculatorTest extends TestCase {
private Calculator cal;
protected void setUp() throws Exception {
cal = new Calculator();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testAdd() {
int result = cal.add(1, 2);
System.out.println("add: " + result);
}
public void testMinus() {
int result = cal.minus(5, 2);
System.out.println("minus: " + result);
}
public void testMultiply() {
int result = cal.multiply(4, 2);
System.out.println("multiply: " + result);
}
public void testDivide() {
int result = 0;
try {
result = cal.divide(10, 5);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("divide: " + result);
}
}
Eclipse中,创建BookTest类有两种方法:方法一,像前边创建Book类一样,点击 文件 - 新建 - 类 来创建;方法二,先在 包资源管理器 中选中Book类,然后点击 文件 - 新建 - JUnit测试用...