今天完成了软件测试的上机,我会在如下的文章中对上述使用进行汇总:
一、Junit 和 Hamcrest 的安装
(1)第一种方法
其实Eclipse是自带Junit的,所以可以直接通过
右击选中的project → build path → add libraries → 选中junit,next直到finish
(2)第二种方法
第二种方法是在官网上直接下载包,通过
右击选中的project → build path → add external JARs ,把两个包引进来
二、Eclemma的安装
通过Help → Elicpse Marketplace
将上述第一个安装即可
三、实验内容
1.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.
写一个判断等边或者等腰三角形的函数。
程序代码已经上传至GitHub
为了防止污染源代码,应该将测试代码和源代码分开,但是至于相同的包内。
2.程序代码如下
package triangleTest; public class triangleExam { public static int judgeTriangle(int a,int b,int c){ int scalene = 3; int equilateral = 2; int isosceles = 1; if(a>0&&b>0&&c>0){ if(a+b>c&&a+c>b&&b+c>a){ if(a==b&&b==c){ System.out.println("This is an euilateral triangle"); return equilateral; }else if(a!=b&&b!=c&&c!=a){ System.out.println("This is a scalene triangle"); return scalene; }else{ System.out.println("This is an isosceles triangle"); return isosceles; } }else { return -1; } } return -1; } }
3.测试代码如下
package triangleTest; import org.junit.*; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class triangleExamTest { static triangleExam tr = new triangleExam(); int scalene = 3; int equilateral = 2; int isosceles = 1; @Before public void setUp() throws Exception { } @Test public void testIsosceles() { assertEquals(tr.judgeTriangle(4, 4, 2),isosceles); } @Test public void testEquilateral() { assertEquals(tr.judgeTriangle(1, 1, 1),equilateral); } @Test public void testScalene() { assertEquals(tr.judgeTriangle(3, 4, 5),scalene); } @Test public void testNotIsosceles() { assertFalse(tr.judgeTriangle(4, 5, 1) == isosceles); //assertFalse(tr.judgeTriangle(5, 5, 5) == isosceles); } @Test public void testNotEquilateral() { assertFalse(tr.judgeTriangle(2, 2, 1) == equilateral); } @Test public void testNotScalene() { assertFalse(tr.judgeTriangle(1, 1, 1) == scalene); assertFalse(tr.judgeTriangle(1, 2, 1) == scalene); assertFalse(tr.judgeTriangle(2, 2, 1) == scalene); assertFalse(tr.judgeTriangle(0, 0, 0) == scalene); } @Test public void testNotTriangle() { assertTrue(tr.judgeTriangle(1, 1, 0) == -1); assertTrue(tr.judgeTriangle(0, 0, 0) == -1); assertTrue(tr.judgeTriangle(-1, -1, 0) == -1); } @Test public void testInvalidTriangle() { assertTrue(tr.judgeTriangle(1, 1, 2) == -1); } }
4.
其中绿色表示已经覆盖,黄色表示部分覆盖。