0

测试夹具的一部分检查在测试期间没有记录错误:

@After
public void testname() {
    if(accumulatedErrors()) {
        fail("Errors were recorded during test");
    }
}

但是对于预期会失败的测试,如下所示:

@Test(expected = IllegalStateException.class)
public void shouldExplode() throws Exception {
    doExplodingStuff();
}

@After 方法应该反转检查:

@After
public void testname() {
    if (failureIsExpected()) {
        assertTrue("No errors were recorded during test", accumulatedErrors());
    } else {
        assertFalse("Errors were recorded during test", accumulatedErrors());
    }
}

有没有办法expected从方法中检查已执行测试的参数@After

当然,测试可以指定expectToFail=true或类似的东西,但我想避免这种重复。

4

2 回答 2

2

为什么不能在每个测试方法中添加assertTrueor ?assertFalse你的解决方案在我看来太复杂了。使用注释的方法@After应该用于释放资源。

于 2013-11-08T09:52:04.717 回答
0

使用catch-exception,您可以将异常检查移动到方法内部而不是方法外部:

@Test
public void shouldExplode() throws Exception {
    catchException(this).doExplodingStuff();
    assertTrue(caughtException() instanceof IllegalStateException);
}
于 2013-11-08T09:52:34.407 回答