软件测试实验一
一、实验任务
Tasks:
- Install Junit(4.12), Hamcrest(1.3) with Eclipse
- Install Eclemma with Eclipse
- Write a java program for the triangle problem and test the program with Junit.
a) Description of triangle problem:
Function triangle takes three integers a,b,c which are length of triangle sides; calculates whether the triangle is equilateral, isosceles, or scalene.
二、实验过程
首先根据要求安装JUunit以及Hamcrest。由于Eclipse中自带Junit,所以并需要额外下载。Eclemma通过Eclipse的商店中直接下载即可。
在完成了基础的准备之后,就可以开始编写代码来解决三角形问题。
编写三个方法,分别用来判定三角形是否等边,是否等腰以及是否不等边。
package triangle; public class judgetriangle { public boolean equilateral(int a, int b, int c){ if(a == b && a == c){ return true; } else { return false; } } public boolean isosceles(int a, int b, int c){ if(a == b || a == c || b == c){ return true; } else { return false; } } public boolean scalene(int a, int b, int c){ if(a != b && a != c){ return true; } else { return false; } } }
在编写完要测试的方法后,结下来就是使用Junit和hamcrest进行测试,步骤如下:
首先在项目上点击右键,在项目的属性中选择java build path,并将Junit单元测试包引入该项目中
在引入了junit之后,用右键点击所写的类弹出菜单,选择“New à JUnit Test Case”。
在选择所需要测试的方法之后,会自动生成一个test文件,同时修改文件中的测试方法后,代码如下:
package triangle; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class judgetriangleTest { private static judgetriangle triangle = new judgetriangle(); @Before public void setUp() throws Exception { } @Test public void testEquilateral() { int a = 1; int b = 1; int c = 1; assertEquals(true,triangle.equilateral(a, b, c)); } @Test public void testIsosceles() { int a = 1; int b = 2; int c = 2; assertEquals(true,triangle.isosceles(a, b, c)); } @Test public void testScalene() { int a = 2; int b = 3; int c = 4; assertEquals(true,triangle.scalene(a, b, c)); } }
之后使用junit进行测试:
运行结果如下:
三个都打钩表示三个方法都测试成功。
接下来使用Eclemma进行覆盖率测试:
在成功安装了Eclemma之后,在工具栏中会多出如下按钮,点击运行:,执行结果如下:
三、实验总结:
为了确保程序中没一个函数功能完全正确,通常需要对函数的方方面面进行测试,然而要对函数进行测试在,传统方法中需要重新另外写一个程序,接着在该程序中调用需要测试的方法,并且观测运行结果是否符合预期,十分麻烦。在有了Junit单元测试包之后,就大大简化了进行单元测试所需要做的工作,对软件测试有极大的帮助。