软件测试—— junit 单元测试

Tasks:

  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.

     EclEmma安装

1. 选择Help->Eclipse Marketplace->搜索EclEmma,Install;

2. 重启eclipse发现工具栏上出现Coverage图标,说明安装成功;2

  EclEmma使用

1. 新建一个项目,然后添加一个类,然后简单书写一些代码;

2. 右键项目->选择Coverage As->Java Application,可以得到如下结果:

3

3. 从运行结果可以看到,有多种颜色,其中

绿色表示代码被执行到

黄色表示代码部分执行到

红色表示代码没有被执行到

3.2 EclEmma检测覆盖率

1. 选择Window->Show View->Other->Java->Coverage可以看到代码执行的覆盖率;

33

2. 其中可以看到每一个类中代码被执行的百分比,见2,也可以看到整个项目代码被执行的百分比,见1;

3. 其中检测覆盖率可以用到单元测试中,查看单元测试覆盖率。

   实验demo

主类:

package text2;

public class triangle {
    public static int text1(int a,int b, int c) {
        
        int array[];
        array= new int[3];
        array[0]= a;
        array[1]= b ;
        array[2]= c;
        
        int temp;
        for(int i = 0 ; i < 3 ; i++)
        {
            for(int j = 0 ; j < 2 ; j++)
            {
                if(array[j]>array[j+1])
                {
                    temp = array[j+1];
                    array[j+1] = array[j];
                    array[j] = temp;
                }
            }
        }
        
        if(array[0]+array[1]>array[2])
        {
            
            if(array[0]==array[1] && array[0]==array[2])
            
                return 3;
            if(array[0]==array[1]||array[1]==array[2])
                
                return 2;
                
            if(array[0]*array[0]+array[1]*array[1]==array[2]*array[2])
                
                return 4;
            return 1;
        }
        
        return 0;
        
        
    }
}

1代表三角形,0代表不构成3角形,2代表等腰三角形,3代表等边三角形,4代表直角三角形

------------在写博客的时候意识到没有判断是否是等腰直角三角形,如果是则先被判断为了等腰三角形。

测试类:

package text2;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ParameterTest {
    int expected = 0;
    int input1 = 0 ;
    int input2 = 0;
    int input3 = 0;
@Parameters
public static Collection<Object[] > t(){
    return Arrays.asList(new Object[][]{
        {0,3,1,2},
        {0,4,2,2},
        {2,2,2,1},
        {3,1,1,1},
        {4,3,4,5},
        {1,6,8,7}
    });
}


public ParameterTest(int expected,int input1,int input2,int input3){
    this.expected = expected;
    this.input1 = input1;
    this.input2 = input2;
    this.input3 = input3;
}
@Test
public void test1(){
    assertEquals(expected, triangle.text1(input1,input2,input3));
}
}


测试结果:

原文地址:https://www.cnblogs.com/wutong2/p/5291767.html