繁体   English   中英

如何在JUnit中捕获异常

[英]How to catch exceptions in JUnit

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

我也试过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块中吞下异常并返回一个空列表。 检查是否发生异常的唯一方法是断言返回的列表为空。

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

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

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

然后你的测试运行正常,因为@Test(expected = Exception.class)将捕获你的异常,继续你的测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM