Har*_*nji 15 java junit unit-testing junit4 try-finally
块writer.close()内的方法是否会finally { }运行Junit断言错误?
假设以下代码:
@Test
public void testWriter() {
try {
writer.open();
final List<MyBean> myBeans = new ArrayList<ProfileBean>();
/** Add 2 beans to the myBeans List here. **/
final int beansWritten = writer.writeBeans(myBeans);
// Say this assertion error below is triggered
org.junit.Assert.assertEquals("Wrong number of beans written.", -1, profilesWritten);
} finally {
writer.close(); // will this block run?
}
}
Run Code Online (Sandbox Code Playgroud)
现在finally()块会像常规流一样运行吗?
dka*_*zel 19
是的,该finally块将运行.Junit断言错误只是正常Exception的,因此通常的java try-catch-finally模式将起作用.(你甚至可以抓住Exception你想要的)