Reputation: 99
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();
}
Upvotes: 3
Views: 566
Reputation: 2805
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:
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
Upvotes: 0
Reputation: 19926
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.
Upvotes: 4