如果抛出JUnit ExpectedException后如何继续测试? [英] How to continue test after JUnit ExpectedException if thrown?
问题描述
我已经使用ExpectedException功能设置了一些JUnit(4.12)测试,我希望测试在预期的异常之后继续。但是我从来没有看到日志'3',因为执行似乎在异常后停止,如果捕获事件?
I have set up some JUnit (4.12) test with the ExpectedException feature, and I would like the test to continue after the expected exception. But I never see the log '3', as the execution seems to stop after the exception, event if catch?
这实际上是否可行,以及如何?
Is this actually possible, and how?
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testUserAlreadyExists() throws Exception {
log.info("1");
// Create some users
userService.createUser("toto1");
userService.createUser("toto2");
userService.createUser("toto3");
Assert.assertTrue( userService.userExists("toto1") );
Assert.assertTrue( userService.userExists("toto2") );
Assert.assertTrue( userService.userExists("toto3") );
log.info("2");
// Try to create an existing user
exception.expect(AlreadyExistsException.class);
userService.createUser("toto1");
log.info("3");
}
推荐答案
你不能这样做,当抛出异常,抛出真实的 ExpectedException
规则。
You cannot do that, when the exception is thrown it's thrown for real, ExpectedException
rule or not.
如果你真的想要这种行为,你可以回到旧学校模式:
If you really want this kind of behaviour, you can go back to the "old school" pattern:
try {
userService.createUser("toto1");
Assert.fail("expecting some AlreadyExistsException here")
} catch (AlreadyExistsException e) {
// ignore
}
log.info("3");
但我不会费心去做一些日志。
But I wouldn't bother for some log.
这篇关于如果抛出JUnit ExpectedException后如何继续测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!