由于 catch block 中的 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();
}
最佳答案
因为您在 catch block 中吞下了异常并返回了一个空列表。检查异常是否发生的唯一方法是断言返回的列表为空。
@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)
。因为永远不会抛出异常。
关于java - 如何在 JUnit 中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56337370/