软件测试实验1:Junit、Hamcrest和Eclemma的理解及应用

实验要求如下:

  1. Install Junit(4.12), Hamcrest(1.3) with Eclipse
  2. Install Eclemma with Eclipse
  3. 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. 

一、在Eclipse中Junit和Hamcrest的安装。

  下载junit-4.12.jar和hamcrest-all-1.3.jar,在建立工程时,在Build Path中加入包及可,如图即可完成安装。

          

二、在Eclipse中安装Eclemma

  1、打开Eclipse,选择Help->Eclipse Marketplace->搜索EclEmma,Install;

  2、2重启eclipse发现工具栏上出现Coverage图标,说明安装成功;操作如下图:

   

安装完成后,工具栏上出现的Coverage图标如图:

三、写测试用例。安要求完成任务

  1、三角形类的实现:

 1 public class Triangle {
 2     private int a,b,c;
 3     
 4     public Triangle() {
 5         super();
 6     }
 7 
 8     public Triangle(int a, int b, int c) {
 9         super();
10         this.a = a;
11         this.b = b;
12         this.c = c;
13     }
14 
15     public String judgeTriangle(int a,int b,int c){
16         if(a+b>c&&a+c>b&&b+c>a){
17             if(a==b&&a==c)return "equilLateral";
18             else if(a==b||a==c||b==c) return "isSosceles";
19             else return "scalene";
20         }
21         else return "notTriangle";
22     }
23 }

  2、简单用例测试:

public class TestCase {
    Triangle t;
    @Test 
    public void test(){
        t = new Triangle(1,1,1);
        assertEquals("equilLateral",t.judgeTriangle(1, 1, 1));
        t = new Triangle(1,2,2);
        assertEquals("isSosceles",t.judgeTriangle(1, 2, 2));
    }
}

  3、参数化用例测试:

 1 @RunWith(Parameterized.class)
 2 public class TestPara {
 3     private int a,b,c;
 4     private String expected;
 5     private Triangle t = null;
 6     public TestPara(int a, int b, int c, String expected) {
 7         super();
 8         this.a = a;
 9         this.b = b;
10         this.c = c;
11         this.expected = expected;
12     }
13     
14     @Before
15     public void setUp(){
16         t = new Triangle();
17     }
18     @Parameters
19     public static Collection<Object[]> getData(){
20         return Arrays.asList(new Object[][]{
21                 {1,1,1,"equilLateral"},
22                 {1,2,2,"isSosceles"},
23                 {2,3,4,"scalene"},
24                 {3,4,1,"notTriangle"},
25                 {3,3,3,"equilLateral"},
26                 {0,3,2,"notTriangle"}
27         });
28     }
29     
30     @Test
31     public void testTriangle(){
32         assertEquals(this.expected,t.judgeTriangle(a, b, c));
33     }
34 }

用Junit Test 方法运行,正确结果如下图左,错误用例提示如下图右:

                

    正确用例运行结果        错误用例运行结果

点击错结果行,可进入错误代码段。

  4、Eclemma的应用。

  正确安装Eclemma后,选择Coverage as方式运行程序,结果将以不同颜色显示代码段,如图:

         

 

其中:绿色表示代码被执行到,黄色表示代码部分执行到,红色表示代码没有被执行到。

选择Window->Show View->Other->Java->Coverage可以看到代码执行的覆盖率如图:

posted @ 2016-03-19 01:58  偶滴个天  阅读(353)  评论(0编辑  收藏  举报