一朽砰、實(shí)驗(yàn)要求
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.
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.
二晒喷、實(shí)驗(yàn)過(guò)程
1角塑、Junit晋柱、Hamcrest羹令、Eclemma的安裝
使用了Idea作為IDE,引入了Junit4.8的Jar包塑径。引入方法為:
File->Project Structrure->Libraries->+按鈕->選擇jar包->確定
對(duì)于Hamcrest衔彻,Junit4.4及以上已經(jīng)集成了Hamcrest框架薇宠。由于我使用的是4.8版本,無(wú)需再安裝
對(duì)于Eclemma艰额,Idea自帶的插件有Idea Code Coverage澄港,不用再安裝其他Code Coverage插件
2、判斷三角形的代碼
我的程序?qū)τ诘冗吶切畏祷?柄沮,對(duì)于非等邊而等腰的三角形返回2回梧,對(duì)于斜三角形返回3废岂,對(duì)于不是三角形的返回4
package hdychi;
public class Triangle {
public static int getType(int a,int b,int c){
if(a == b && b == c){
System.out.println(1);
return 1;
}
else{
if(a == b){
if(a + b > c){
System.out.println(2);
return 2;
}
}
else if(b == c){
if(b + c > a){
System.out.println(2);
return 2;
}
}
else if(a == c){
if(a + c > b){
System.out.println(2);
return 2;
}
}
}
if(a + b > c && Math.abs(a - b) < c){
System.out.println(3);
return 3;
}
System.out.println(4);
return 4;
}
}
3、進(jìn)行測(cè)試
我設(shè)計(jì)的樣例包括等邊三角形狱意,三個(gè)不同兩條邊相等的等腰三角形
代碼如下:
package hdychi;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class Test {
@org.junit.Test
public void testNormal(){
int res1 = Triangle.getType(1,1,1);//測(cè)試等邊三角形
assertEquals(1,res1);
int res2 = Triangle.getType(2,2,1);//測(cè)試等腰三角形
assertEquals(2,res2);
res2 = Triangle.getType(1,2,2);//換兩條邊等腰
assertEquals(2,res2);
res2 = Triangle.getType(2,1,2);//換兩條邊等腰
assertEquals(2,res2);
int res3 = Triangle.getType(3,4,5);//測(cè)試斜邊三角形
assertEquals(3,res3);
int res4 = Triangle.getType(2,2,4);//測(cè)試不是三角形的
assertEquals(4,res4);
assertThat(res4,equalTo(4));
}
}
4湖苞、測(cè)試結(jié)果
由圖可見(jiàn),測(cè)試覆蓋率為97%详囤,每個(gè)分支都達(dá)到了财骨,且無(wú)錯(cuò)誤