JUnit - 在@After部分中捕获异常

时间:2014-11-18 07:31:26

标签: junit exception-handling try-catch

我有这种情况,其中一些测试会抛出不同的例外。

@Test
public void addDevice(){
    device.addDevice(); // this may throw exception 1
    device.verifyStatus("Ready");
    device.open();  // this may throw exception 2
    device.verifyStatus("Open"); 
}

@Test
public void otherTest(){
    device.act(); // this may throw exception 3
    device.verifyStatus("Ready");
}

@After
public void tearDown(){
    // handle the exception here
}

我想在@After部分处理这些例外情况,而不用trycatch包装测试。

这可能吗?

2 个答案:

答案 0 :(得分:1)

不,这是不可能的。

你可以使用try-catch-block来包装测试。然后,您可以将异常存储到成员变量而不是处理它。 在@After方法中,您可以检查异常是否为空。

答案 1 :(得分:0)

由于您的评论,您使用此代码进行了数百次测试,我认为这是设置逻辑,实际应该采用@Before方法。

因此,您可以使用before和after方法指定外部资源规则:https://github.com/junit-team/junit/wiki/Rules#externalresource-rules

before()方法中执行设置,捕获并存储异常,并使用after()方法处理它们。

但是稍后处理异常是否有意义?如果设置失败,您能否成功运行测试用例?

相关问题