实验要求:
- 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.
实验过程:
安装Junit、Eclemma需要Java的IDE环境,本机已经安装过Eclipse,版本为Java EE 4.5.0。
安装Junit、Hamcrest:
1.下载了三个.jar文件,hamcrest-core-1.3rc2.jar、hamcrest-library-1.3.rc2.jar以及junit-4.12.jar。
2.在Eclipse中新建Java工程,并将三个.jar引入工程中。
安装Eclemma:
使用Eclipse Marketplace,寻找Eclemma并直接下载安装。
使用Junit及Eclemma:
首先编写解决三角问题的代码,如下:
public class JudgeTriangle { static public String EQUILATERAL = "equilateral",ISOSCELES = "isosceles",SCALENE = "scalene",ERROR = "error"; public String judgeTriangle(float a,float b,float c){ if(a <= 0 || b <= 0 || c <= 0 || a + b <= c || a + c <= b || b + c <= a){ return ERROR; } boolean[] judge = {a==b,b==c,c==a}; int count = 0; for(int i = 0;i < judge.length;++i){ if(judge[i])++count; } switch(count){ case 3:return EQUILATERAL;//equilateral,0 case 1:return ISOSCELES;//isosceles,1 case 0:return SCALENE;//scalene,2 default:return ERROR;//error,-1 } } }
之后创建Junit Test Case,选择要测试的类以及类中要进行测试的函数,填入test case的类名,创建。
编写测试用例,这里测试了五组数据,测试函数如下:
@Test public void testTest() { System.out.println("@Test"); JudgeTriangle jt = new JudgeTriangle(); assertEquals(JudgeTriangle.EQUILATERAL,jt.judgeTriangle(3,3,3)); assertEquals(JudgeTriangle.ISOSCELES,jt.judgeTriangle(2,2,3)); assertEquals(JudgeTriangle.SCALENE,jt.judgeTriangle(2,3,4)); assertEquals(JudgeTriangle.ERROR,jt.judgeTriangle(0,1,2)); assertEquals(JudgeTriangle.ERROR,jt.judgeTriangle(0,0,0)); }
选择Run As -> Junit Test,结果如下图。绿色是完全通过测试的,黄色是部分通过测试而未完全通过,想必是没有完全覆盖分支,红色是完全没测试过的语句。
用例表:
|
输入 |
期望输出 |
实际输出 |
1 |
3,3,3 |
"equilateral" |
"equilateral" |
2 |
2,2,3 |
"isosceles" |
"isosceles" |
3 |
2,3,4 |
scalene" |
scalene" |
4 |
0,1,2 |
"error" |
"error" |
5 |
0,0,0 |
"error" |
"error" |
时间: 2024-10-10 23:12:53