【问题标题】:How to catch exceptions in JUnit如何在 JUnit 中捕获异常
【发布时间】:2019-05-28 07:47:51
【问题描述】:

由于我在 catch 块中的 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();
  }

【问题讨论】:

  • 您正在捕获Exception 并在catch 块中返回new ArrayList&lt;&gt;()。这意味着,您不能断言任何 Exception

标签: java exception junit


【解决方案1】:

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

@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)。因为永远不会抛出异常。

【讨论】:

  • 检查是否发生异常的唯一方法是断言返回的列表为空:我不同意,您可以使用OP发布的注释,您发布的解决方案是一种可能,而不是唯一一种:) ...看我的回答,+1 tho
  • @Leviand 我不同意你的不同意见:P 我似乎不是一个好主意来更改生产代码(抛出任何异常并且不记录任何内容),这样你的测试就不会失败
  • Ofc 如果这是一个生产代码你是对的,但如果问题是关于“为什么我的注释不起作用”,那么这不是唯一的方法。 Ty 澄清一下!
【解决方案2】:

您正在使用 try-catch 块捕获异常,因此 throw 永远不会到达测试方法:您需要做的只是删除该 try catch:

public ArrayList<Action> parsePlaByPlayTable() {
    //...
    document = Jsoup.connect(url).get();
    //...
}

那么您的测试将运行良好,因为@Test(expected = Exception.class) 将捕获您的异常,并成功完成您的测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    相关资源
    最近更新 更多