(1)自动生成的CalculatorTest类
(2)修改和完善Calculator类
(3)Point2d的测试用例
(一)修改之前的Calculator的测试结果:
(1)自动生成的CalculatorTest类 代码:
package andycpp;
public class Calculator {
private static int result; // 静态变量,用于存储运行结果
public void add(int n) {
result = result + n;
}
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;
}
}
修改之后的Calculator的测试结果:
Calculator的代码完善
修改后的Calculator的测试用例:
加法:操作数:2,、3;结果:5
减法:操作数:10、2;结果:8
乘法:操作数:10、2;结果:20
除法:操作数:8、2;结果:4
平方:操作数:3;结果:9
开方:操作数:4;结果:2
代码:
package andycpp;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class CalculatorTest {
private static Calculator calculator = new Calculator();
@Before
public void setUp() throws Exception {
calculator.clear();
}
@Test
public void testAdd() {
calculator.add(2);
calculator.add(3);
assertEquals(5, calculator.getResult());
}
@Test
public void testSubstract() {
calculator.add(10);
calculator.substract(2);
assertEquals(8, calculator.getResult());
}
@Test
public void testMultiply() {
calculator.add(10);
calculator.multiply(2);
assertEquals(20, calculator.getResult());
}
@Test
public void testDivide() {
calculator.add(8);
calculator.divide(2);
assertEquals(4, calculator.getResult());
}
@Test
public void testSquare() {
calculator.square(3);
assertEquals(9, calculator.getResult());
}
@Test
public void squareRoot() {
calculator.squareRoot(4);
assertEquals(2, calculator.getResult());
}
}
运行结果:
Calculator的代码完善后试验结果
(二)Point2d的测试用例:
测试用例1: pt1 = (0.0, 0.0)
pt2 = (4.0, 3.0)
测试代码:
package andycpp;
publicclass Point2d {
privatedoublex;
privatedoubley;
privatedoublez;
public Point2d() {
}
public Point2d(doublex, doubley) {
this.x = x;
this.y = y;
}
publicdouble DistanceFrom(Point2d p) {
return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y));
}
publicstaticdouble DistanceFrom(Point2d p1, Point2d p2) {
returnp1.DistanceFrom(p2);
}
publicdouble DistanceFromOrgin() {
return Math.sqrt(x * x + y * y);
}
}
Point2d的测试用例测试结果: