白盒测试JUnit的使用

JUnit测试

1 Fixture 是指在执行一个或者多个测试方法时需要的一系列公共资源或者数据,例如测试环境,测试数据等等。
公共 Fixture 的设置也很简单,您只需要:
@Before @After
使用注解 org,junit.Before 修饰用于初始化 Fixture 的方法。
使用注解 org.junit.After 修饰用于注销 Fixture 的方法。
保证这两种方法都使用 public void 修饰,而且不能带有任何参数。
注意是每一个测试方法的执行都会触发对公共 Fixture 的设置,也就是说使用注解 Before 或者 After 修饰的公共 Fixture 设置方法是方法级别的。

所以后来引入了类级别的fixture
@BeforeClass  @AfterClass
使用注解 org,junit.BeforeClass 修饰用于初始化 Fixture 的方法。
使用注解 org.junit.AfterClass 修饰用于注销 Fixture 的方法。
保证这两种方法都使用 public static void 修饰,而且不能带有任何参数。

2 异常以及时间测试expected 和 timeout
@Test(expected=UnsupportedDBVersionException.class) 
public void unsupportedDBCheck(){ 
…… 
} 

最长运行时间为
@Test(timeout=1000) 
public void selfXMLReader(){ 
…… 
} 

3 忽略测试方法 ignore
@ Ignore(“db is down”) 
@Test(expected=UnsupportedDBVersionException.class) 
public void unsupportedDBCheck(){ 
…… 
} 

4 测试运行器--JUnit 中所有的测试方法都是由它负责执行的
JUnit 为单元测试提供了默认的测试运行器,但 JUnit 并没有限制您必须使用默认的运行器。
@RunWith(CustomTestRunner.class) 
public class TestWordDealUtil { 
…… 
} 

5 测试套件
创建一个空类作为测试套件的入口。
使用注解 org.junit.runner.RunWith 和 org.junit.runners.Suite.SuiteClasses 修饰这个空类。
将 org.junit.runners.Suite 作为参数传入注解 RunWith,以提示 JUnit 为此类使用套件运行器执行。
将需要放入此测试套件的测试类组成数组作为注解 SuiteClasses 的参数。
保证这个空类使用 public 修饰,而且存在公开的不带有任何参数的构造函数。

package com.ai92.cooljunit; 
import org.junit.runner.RunWith; 
import org.junit.runners.Suite; 
…… 
/** 
* 批量测试工具包中测试类 
* @author Ai92 
*/ 
@RunWith(Suite.class) 
@Suite.SuiteClasses({TestWordDealUtil.class}) 
public class RunAllUtilTestsSuite { 
} 

6 参数化测试

为准备使用参数化测试的测试类指定特殊的运行器 org.junit.runners.Parameterized。
为测试类声明几个变量,分别用于存放期望值和测试所用数据。
为测试类声明一个使用注解 org.junit.runners.Parameterized.Parameters 修饰的,返回值为 java.util.Collection 的公共静态方法,并在此方法中初始化所有需要测试的参数对。
为测试类声明一个带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。
编写测试方法,使用定义的变量作为参数进行测试。

package com.ai92.cooljunit; 
import static org.junit.Assert.assertEquals; 
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 TestWordDealUtilWithParam { 
private String expected; 
private String target; 
@Parameters 
public static Collection words(){ 
return Arrays.asList(new Object[][]{ 
{"employee_info", "employeeInfo"}, //测试一般的处理情况 
{null, null}, //测试 null 时的处理情况
{"", ""}, 
{"employee_info", "EmployeeInfo"}, //测试当首字母大写时的情况 
{"employee_info_a", "employeeInfoA"}, //测试当尾字母为大写时的情况 
{"employee_a_info", "employeeAInfo"} //测试多个相连字母大写时的情况 
}); 
} 
/** 
* 参数化测试必须的构造函数 
* @param expected 期望的测试结果,对应参数集中的第一个参数 
* @param target 测试数据,对应参数集中的第二个参数 
*/ 
public TestWordDealUtilWithParam(String expected , String target){ 
this.expected = expected; 
this.target = target; 
} 

猜你喜欢

转载自ottoliu.iteye.com/blog/1188495