简体   繁体   English

如何在JUnit中捕获异常

[英]How to catch exceptions in JUnit

My JUnit test does not catch the exception because of my return statement in the catch block. 由于catch块中的return语句,我的JUnit测试没有捕获异常。 When I delete returning statement, the test passes. 当我删除return语句时,测试通过。 I want my unit test to work with returning statement if the exception occurs. 如果发生异常,我希望我的单元测试能够使用return语句。

I've also tried JUnit 5 stuff but it does not fix the problem. 我也试过JUnit 5的东西,但它没有解决问题。

My method: 我的方法:

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. . .
}

My test: 我的测试:

  @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();
  }

Because you're swallowing the exception in your catch block and returning an empty list. 因为你在catch块中吞下异常并返回一个空列表。 The only way to check if the exception occured is to assert that the returned list is empty. 检查是否发生异常的唯一方法是断言返回的列表为空。

@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());
}

You also need to remove (expected = Exception.class) from your @Test annotation. 您还需要从@Test注释中删除(expected = Exception.class) Because an exception will never be thrown. 因为永远不会抛出异常。

You are catching the exception with try-catch block, so that throw will never reach the test method: all you need to do is just remove that try catch: 您正在使用try-catch块捕获异常,因此throw将永远不会到达测试方法:您需要做的就是删除try try:

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

then your test will run fine, since @Test(expected = Exception.class) will catch your exception, succeeding your test 然后你的测试运行正常,因为@Test(expected = Exception.class)将捕获你的异常,继续你的测试

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

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