How to catch exceptions in JUnit

Dejan Ilic :

My JUnit test does not catch the exception because of my return statement in the catch block. When I delete returning statement, the test passes. I want my unit test to work with returning statement if the exception occurs.

I've also tried JUnit 5 stuff but it does not fix the problem.

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

Because you're swallowing the exception in your catch block and returning an empty list. 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. Because an exception will never be thrown.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92660&siteId=1