java - 如何在 JUnit 中捕获异常

标签 java exception junit

由于 catch block 中的 return 语句,我的 JUnit 测试没有捕获异常。当我删除返回语句时,测试通过。如果发生异常,我希望我的单元测试能够使用返回语句。

我也尝试过 JUnit 5 的东西,但它没有解决问题。

我的方法:

public ArrayList<Action> parsePlaByPlayTable() {
    ArrayList<Action> actions = new ArrayList<>();
    Document document = null;

    try {
      document = Jsoup.connect(url).get();
    } catch (Exception e) {
      log.error(e.getMessage());
      return new ArrayList<>();
    }

    // if the exception occurs and there is no return in the catch block,
    // nullPointerException is thrown here
    Element table = document.getElementById("pbp"); 

    // more code. . .
}

我的测试:

  @Test(expected = Exception.class)
  public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
  }

最佳答案

因为您在 catch block 中吞下了异常并返回了一个空列表。检查异常是否发生的唯一方法是断言返回的列表为空。

@Test
public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
    Assert.assertTrue(actions.isEmpty());
}

您还需要从 @Test 注释中删除 (expected = Exception.class)。因为永远不会抛出异常。

关于java - 如何在 JUnit 中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56337370/

相关文章:

java - 在 do while 循环中尝试 catch

java - JUnit 中用于 ShoppingCart 的无序执行测试

java - 获取符号之间的字符串

java - Jersey - 在运行时设置 REST 响应编码

java - Web服务器/容器相对于EJB和Entities等其他类如何对待POJO?

Java:从 X 到 Y 的未经检查的转换/如何实现 castOrNull

php - 如何检查PHPUnit正确抛出的异常?

Android NDK 和 C++ 异常 : current status?

java - 如何 stub 一个以泛型类作为参数的方法?

java - 如何在 JUnit 中重用方法和测试?