JUnit 测试用例中“失败”的实际用途是什么?
我发现它有用的一些情况:
标记一个不完整的测试,所以它会失败并警告你直到你完成它
确保抛出异常:
try{ // 做事... fail("没有抛出异常"); }catch(Exception e){ assertTrue(e.hasSomeFlag()); }
笔记:
从 JUnit4 开始,有一种更优雅的方法来测试是否抛出了异常:使用注解 @Test(expected=IndexOutOfBoundsException.class)
但是,如果您还想检查异常,这将不起作用,那么您仍然需要 fail()
。
假设您正在为负流编写测试用例,其中被测试的代码应该引发异常。
try{
bizMethod(badData);
fail(); // FAIL when no exception is thrown
} catch (BizException e) {
assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}
我认为通常的用例是在否定测试中没有抛出异常时调用它。
类似于以下伪代码:
test_addNilThrowsNullPointerException()
{
try {
foo.add(NIL); // we expect a NullPointerException here
fail("No NullPointerException"); // cause the test to fail if we reach this
} catch (NullNullPointerException e) {
// OK got the expected exception
}
}
我在 @Before 方法中可能出现问题的情况下使用了它。
public Object obj;
@Before
public void setUp() {
// Do some set up
obj = new Object();
}
@Test
public void testObjectManipulation() {
if(obj == null) {
fail("obj should not be null");
}
// Do some other valuable testing
}
@Before
方法成功,最好直接在该方法中进行检查。作为奖励,至少 JUnit 和 TestNG 甚至会针对来自 @Before
/@After
方法的错误报告不同的失败,因此可以看出问题不在于测试本身。
这就是我使用 Fail 方法的方式。
您的测试用例最终可能处于三种状态
Passed : 被测函数执行成功,返回数据符合预期 Not Passed : 被测函数执行成功,但返回数据不符合预期 Failed : 函数没有执行成功,this 不是
预期的(与预期会发生异常的负面测试用例不同)。
如果您使用的是 Eclipse,则三个状态分别由绿色、蓝色和红色标记指示。
对于第三种情况,我使用了失败操作。
例如:public Integer add(integer a, Integer b) { return new Integer(a.intValue() + b.intValue())}
通过案例:a = new Interger(1), b= new Integer(2) 并且函数返回 3 未通过案例:a = new Interger(1), b= new Integer(2) 并且函数返回的 soem 值不是3 失败案例: a =null , b= null 并且函数抛出 NullPointerException
fail()
。
例如,我使用 fail()
表示尚未完成的测试(它发生了);否则,它们将显示为成功。
这可能是因为我不知道 NUnit 中存在某种不完整()功能。
在并发和/或异步设置中,您可能想要验证某些方法(例如委托、事件侦听器、响应处理程序,您可以命名)是否没有调用。除了模拟框架,您可以在这些方法中调用 fail()
以使测试失败。在这种情况下,超时超时是另一种自然故障情况。
例如:
final CountDownLatch latch = new CountDownLatch(1);
service.asyncCall(someParameter, new ResponseHandler<SomeType>() {
@Override
public void onSuccess(SomeType result) {
assertNotNull(result);
// Further test assertions on the result
latch.countDown();
}
@Override
public void onError(Exception e) {
fail(exception.getMessage());
latch.countDown();
}
});
if ( !latch.await(5, TimeUnit.SECONDS) ) {
fail("No response after 5s");
}
最重要的用例可能是异常检查。
虽然 junit4 包含用于检查是否发生异常的 expected element,但它似乎不是较新的 junit5 的一部分。使用 fail()
而不是 expected
的另一个优点是您可以将它与 finally
结合使用,从而进行测试用例清理。
dao.insert(obj);
try {
dao.insert(obj);
fail("No DuplicateKeyException thrown.");
} catch (DuplicateKeyException e) {
assertEquals("Error code doesn't match", 123, e.getErrorCode());
} finally {
//cleanup
dao.delete(obj);
}
如另一条评论所述。在您完成实施之前让测试失败听起来也很合理。