Java 如何在JUnit中捕获异常
我的JUnit测试没有捕获异常,因为我的return语句位于catch块中。当我删除返回语句时,测试通过。如果发生异常,我希望我的单元测试使用返回语句 我也尝试过JUnit5的东西,但它并没有解决这个问题 我的方法:Java 如何在JUnit中捕获异常,java,exception,junit,Java,Exception,Junit,我的JUnit测试没有捕获异常,因为我的return语句位于catch块中。当我删除返回语句时,测试通过。如果发生异常,我希望我的单元测试使用返回语句 我也尝试过JUnit5的东西,但它并没有解决这个问题 我的方法: public ArrayList<Action> parsePlaByPlayTable() { ArrayList<Action> actions = new ArrayList<>(); Document document =
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. . .
}
public ArrayList parsePlaByPlayTable(){
ArrayList操作=新建ArrayList();
单据=空;
试一试{
document=Jsoup.connect(url.get();
}捕获(例外e){
log.error(例如getMessage());
返回新的ArrayList();
}
//如果发生异常并且catch块中没有返回,
//此处抛出nullPointerException
元素表=document.getElementById(“pbp”);
//更多代码。
}
我的测试:
@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();
}
@Test(预期为异常.class)
public void testParsePlaybyPlaytableInvalidURL(){
PlayByPlayActionHtmlParser=新的PlayByPlayActionHtmlParser(“https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
ArrayList actions=parser.parsePlaybyPlaytable();
}
因为您正在捕获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());
}
@测试
public void testParsePlaybyPlaytableInvalidURL(){
PlayByPlayActionHtmlParser=新的PlayByPlayActionHtmlParser(“https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
ArrayList actions=parser.parsePlaybyPlaytable();
Assert.assertTrue(actions.isEmpty());
}
您还需要从
@Test
注释中删除(预期=Exception.class)
。因为永远不会抛出异常。您正在使用try-catch块捕获异常,因此throw永远不会到达测试方法:您只需删除该try-catch:
public ArrayList<Action> parsePlaByPlayTable() {
//...
document = Jsoup.connect(url).get();
//...
}
public ArrayList parsePlaByPlayTable(){
//...
document=Jsoup.connect(url.get();
//...
}
然后您的测试将正常运行,因为
@test(expected=Exception.class)
将捕获您的异常,测试成功您将捕获异常
,并在捕获
块中返回一个新的ArrayList()
。这意味着,您不能断言任何异常
。检查是否发生异常的唯一方法是断言返回的列表为空:我不同意,您可以使用OP发布的注释,您发布的解决方案是可能的,而不是唯一的:)。。。见我的答案,+1tho@Leviand我不同意你的不同意见:P我似乎不是一个好主意来更改生产代码(抛出任何异常,不记录任何内容),这样你的测试不会失败C如果这是生产代码,你是对的,但是如果问题是关于“为什么我的注释不起作用”,那这不是唯一的办法。顺便说一句,请澄清!