phpboy 2011-10-10
JUnit测试
1Fixture是指在执行一个或者多个测试方法时需要的一系列公共资源或者数据,例如测试环境,测试数据等等。
公共Fixture的设置也很简单,您只需要:
@Before@After
使用注解org,junit.Before修饰用于初始化Fixture的方法。
使用注解org.junit.After修饰用于注销Fixture的方法。
保证这两种方法都使用publicvoid修饰,而且不能带有任何参数。
注意是每一个测试方法的执行都会触发对公共Fixture的设置,也就是说使用注解Before或者After修饰的公共Fixture设置方法是方法级别的。
所以后来引入了类级别的fixture
@BeforeClass@AfterClass
使用注解org,junit.BeforeClass修饰用于初始化Fixture的方法。
使用注解org.junit.AfterClass修饰用于注销Fixture的方法。
保证这两种方法都使用publicstaticvoid修饰,而且不能带有任何参数。
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;
}