《Junit单元测试实验报告》由会员分享,可在线阅读,更多相关《Junit单元测试实验报告(6页珍藏版)》请在金锄头文库上搜索。
1、实验二 Junit单元测试实验报告实验内容: 利用 Junit 对实验程序Point2d.java 进行单元测试实验目的: 掌握单元测试的方法,掌握在Eclipse 里进行 Junit 测试的技术。实验步骤和结果:1、修改之前的Calculator 的测试结果:(1)自动生成的CalculatorTest 类 代码:package andycpp; publicclass Calculator privatestaticintresult; / 静态变量,用于存储运行结果publicvoid add(int n) result = result + n; publicvoid substrac
2、t(int n) result = result - 1; /Bug: 正确的应该是 result =result-n publicvoid multiply(int n) / 此方法尚未写好publicvoid divide(int n) result = result / n; publicvoid square(int n) result = n * n; publicvoid squareRoot(int n) for (; ;) ; /Bug : 死循环 publicvoid clear() / 将结果清零result = 0; publicint getResult() retur
3、nresult; 精选文档2 (2)运行结果:自动生存的测试类完善测试类后的运行结果精选文档3 2、修改和完善Calculator 类:package andycpp; publicclass Calculator privatestaticintresult; / 静态变量,用于存储运行结果publicvoid add( int n) result = result + n; publicvoid substract(int n) result = result - n; /Bug: 正确的应该是 result =result-n publicvoid multiply(int n) res
4、ult = result*n; publicvoid divide(int n) result = result / n; publicvoid square(int n) result = n * n; publicvoid squareRoot(int n) result=( int)Math.sqrt (n); /Bug : 死循环 publicvoid clear() / 将结果清零result = 0; publicint getResult() returnresult; 3、修改后的Calculator 的测试用例:(1)加法:操作数:2,、3;结果: 5 (2)减法:操作数:1
5、0、2;结果: 8 (3)乘法:操作数:10、2;结果: 20 (4)除法:操作数:8、2;结果: 4 (5)平方:操作数:3;结果: 9 (6)开方:操作数:4;结果: 2 代码:package andycpp; import static org.junit.Assert.*; 精选文档4 import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class CalculatorTest private static Calculator calculator = new Calculat
6、or(); 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 pu
7、blic 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 精选文档5 public void testSquare() calculator.square(3); assertEquals(9, calcu
8、lator.getResult(); Test public void squareRoot() calculator.squareRoot(4); assertEquals(2, calculator.getResult(); 4、修改后的Calculator 的测试结果:结果正确5、Point2d 的测试用例:测试用例 1: pt1 = (0.0, 0.0) pt2 = (4.0, 3.0)importstatic org.junit.Assert.*; import org.junit.Before; import org.junit.Test; publicclass Point2dT
9、est privatestatic Point2d pt1 =new Point2d(); privatestatic Point2d pt2 =new Point2d(4.0,3.0); 精选文档6 Beforepublicvoid setUp() throws Exception Testpublicvoid testDistanceFrom() assertEquals(5, pt1 .distanceFrom(pt2 ),0.1); Testpublicvoid testDistanceFromOrigin() assertEquals(5, pt2 .distanceFromOrigin(),0.1); 6、Point2d 的测试结果:两个测试用例结果均正确