我有一些junit测试,这些测试会创建一些应该关闭的资源。

实现此逻辑的一种方法是使用@Before@After方法。

我所做的是将创建内容封装在一些实用程序类中以供重用。例如:

class UserCreatorTestUtil implements AutoClosable {
  User create() {...}
  void close() {...}
}

重点在于对象可以自行关闭,而不需要记住在@After中将其关闭。

用法应为:
@Test
void test() {
  try (UserCreatorTestUtil userCreatorTestUtil = new UserCreatorTestUtil()) {
    User user = userCreatorTestUtil.create();
    // Do some stuff regarding the user's phone
    Assert.assertEquals("123456789", user.getPhone());
  }
}

问题在于junit的assert关键字抛出Error而不是Exception

是否可以使用try-with-resource捕获Error并调用close方法?

*在try-with-resources documentation中找不到答案。

最佳答案

它没有catch任何东西。但是finally确实关闭了所有资源。
finally阻止are run even when an Error is thrown

08-04 19:11