(1)在项目中引入Jar包
(2)编写需要测试的类
public class Calculator {
private static int result=0; // 静态变量,用于存储运行结果
public int add(int n) {
result = result + n;
return result;
}
public void substract(int n) {
result = result - 1; //Bug: 正确的应该是 result =result-n
}
public void multiply(int n) {
} // 此方法尚未写好
public void divide(int n) {
result = result / n;
}
public void square(int n) {
result = n * n;
}
public void squareRoot(int n) {
// for (; ;) ; //Bug : 死循环
}
public void clear() { // 将结果清零
result = 0;
}
public int getResult() {
return result;
}
}
(3)将鼠标点在要测试的类上单击->new->JUnit Test Case
(4)勾选要测试的方法
(5)测试方法生成
(6)修改测试方法体
public class CalculatorTest {
@Before
public void setUp() throws Exception {
}
@Test
public void testAdd() {
Calculator cal = new Calculator();
int result = cal.add(5);
Assert.assertEquals("加法有问题",5, result);
//fail("Not yet implemented");
}
@Test
public void testSubstract() {
fail("Not yet implemented");
}
@Test
public void testMultiply() {
fail("Not yet implemented");
}
@Test
public void testDivide() {
fail("Not yet implemented");
}
@Test
public void testSquare() {
fail("Not yet implemented");
}
@Test
public void testSquareRoot() {
fail("Not yet implemented");
}
@Test
public void testClear() {
fail("Not yet implemented");
}
@Test
public void testGetResult() {
fail("Not yet implemented");
}
}
(7)在生成的测试类的测试方法上单击->run as ->JUnit Test