单元测试
一、概述
1、 单元测试(模块测试)是开发者编写的一小段代码,用于检验被测代码的一个很小的、很明确的功能是否正确。
2、一般认为,在结构化程序时代,单元测试所说的单元是指函数,在当今的面向对象时代,单元测试所说的单元是指类。以我的实践来看,以类作为测试单位,复杂度高,可操作性较差,因此仍然主张以函数作为单元测试的测试单位
3、有一种看法是,只测试类的接口(公有函数),不测试其他函数,从面向对象角度来看,确实有其道理,但是,测试的目的是找错并最终排错,因此,只要是包含错误的可能性较大的函数都要测试,跟函数是否私有没有关系
二、单元测试设计思想
1、单元测试可以借鉴类似功能测试的思想来进行设计
2、一个待测试类当作一个功能块,待测试类当中的方法当作一个小的功能点,
单元测试就理解为对这个待测试方法进行场景设计,编写代码,查看执行各场景结果和场景覆盖率
3、单元测试场景设计可以采用因果分析的方法,将各个参数的组合当作各条件组合,将输入参数后执行方法的结果当作是各条件组合后的结果
三、单元测试设计(采用因果分析法)
1、确定待测试模块即建立测试类
Game类及对应的Game测试类
package test.testDemo;
public class Game {
public String winGame(int num1,int num2) {
int num=num1-num2;
String txt=null;
if(num>0) {
txt="夺奖成功!";
}else if(num==0) {
txt="安慰奖!";
}else {
txt="夺奖失败!";
}
return txt;
}
}
package test.testDemo;
import static org.junit.Assert.*;
import org.junit.Test;
public class GameTest {
@Test
public void testWinGame() {
fail("Not yet implemented");
}
}
2、分析因果条件列出场景并进行用例设计

3、单元测试用例编写
3.1 参数化
3.1.1 引入待测试类,定义参数
3.1.2 引入注解@RunWith(Parameterized.class)参数化测试类
3.1.3 编写需用到的参数的构造函数
3.1.4 编写参数数据初始化方法
package test.testDemo;
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)参数化测试类
@RunWith(Parameterized.class)
public class GameTest {
//引入待测试类,定义参数
private Game game=new Game();
private int num1;
private int num2;
private String expected;
//编写需用到的参数的构造函数
public GameTest(int num1, int num2,String expected) {
super();
this.num1 = num1;
this.num2 = num2;
this.expected=expected;
}
//编写参数数据初始化方法
@Parameters
public static Collection<Object[]> data(){
return Arrays.asList(new Object[][] {{2,1,"夺奖成功!"},{2,2,"安慰奖!"},{1,2,"夺奖失败!"}});
}
@Test
public void testWinGame() {
}
}
3.2 编写单元测试方法
@Test
public void testWinGame() {
String txt=game.winGame(num1, num2);
Assert.assertEquals(expected, txt);
}
四、执行单元测试用例,检查覆盖率,覆盖率需eclipse中安装EclEmma插件
1、选中测试类》右键选中Coverage As》Junit Test
2、执行结果如下



浙公网安备 33010602011771号