链接:
Before和After
在@Before中初始化测试资源
在@After中释放测试资源
Calculate calculate;
@Before
public void setUp() throws Exception {
calculate = new Calculate();
}
@After
public void tearDown() throws Exception {
calculate = null;
}
@Test
public void testPlus(){
assertEquals(3,calculate.plus(1,2));
}
为什么要使用before和after?
用来保证test方法执行前会创建新的test实例,实例变量状态不会传递给下一个test方法。单个test方法执行前后会执行before和after方法。
同时还有@BeforeClass和@AfterClass静态方法,在所有测试开始前后执行。一般是做比较耗时的操作例如创建删除数据库等。对于上述四种方法的执行时间可以这样去理解。
异常测试
使用@Test(excepted = Exception.class)
参数化测试
如果待测数据的输入和输出是一组数据:
可以把测试数据组织起来,用不同的测试数据调用相同的方法。
demo:
@RunWith(Parameterized.class)
public class AbsTest{
@Parameters
public static Collection<?> data(){
return Arrays.asList(new Object[][]{
{0,1},{1,1},{-1,1}
}
}
int input;
int excepted;
public AbsTest(int input, int excepted){
this.input = input;
this,excepted = excepted;
}
}
@Test
public void testAbs(){
int r = Math.abs(this.input);
assertEquals(this.excepted,r);
}
注意:
- 参数必须由静态方法data返回,返回类型为Collection<Object[]>,可用问号表示。
- 静态方法必须标记@Parameters
- 测试类必须标记@RunWith(Parameterized.class)
- 构造方法参数必须与测试参数对应
超时测试
使用@Test(timeout = 1000) 设置超时,其中timeout的单位为ms。
注意的是,超时测试不能取代性能和压力测试。