检查是否引发了异常,并在引发异常后继续



我想做一个测试,从文件中读取一些数据,并将这些数据传递给函数。该函数调用其他方法,其中一些方法抛出一些异常。我感兴趣的是如何检查用文件中的参数调用方法是否在某个地方触发了IOException。我知道提供的代码片段将停止执行,因为我使用了assert。如果我想在不停止测试执行的情况下检查是否抛出了IOException,如果抛出了,我应该如何编写以获取错误消息?谢谢

void test() throws IOException {
Service service = helperFunction();
File articles = new File("file.txt");
Scanner scanner = new Scanner(articles);
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
line = line.replaceAll("[^\d]", " ");
line = line.trim();
line = line.replaceAll(" +", " ");
String[] numberOnTheLine = line.split(" ");
List<Integer> list = Arrays.stream(numberOnTheLine).map(Integer::valueOf).collect(Collectors.toList());
Article article = new Article(Long.valueOf(list.get(0)),
new HashSet<>(List.of(new Version(list.get(1)))));
List<List<Article>> listOfArticles = Collections.singletonList(List.of(article));
Assertions.assertThrows(IOException.class,
() -> service.etlArticles(listOfArticles.stream().flatMap(List::stream).collect(Collectors.toList())));
}
}

简单;try/catch语句会处理它。

替换此:

service.etlArticles(listOfArticles.stream().flatMap(List::stream).collect(Collectors.toList())));

带:

try {

service.etlArticles(listOfArticles.stream().flatMap(List::stream).collect(Collectors.toList())));
} catch (IOException e) {
// Code jumps to here if an IOException occurs during the execution of anything in the try block
}

例如,如果您愿意,您可以自由地进行一些日志记录,然后只进行Assert.fail

assertThrows很简单,它所做的就是:

try {
runThatCode();
} catch (Throwable e) {
if (e instanceof TypeThatShouldBeThrown) {
// Great, that means the code is working as designed, so, just...
return;
}
// If we get here, an exception was thrown, but it wasn't the right type.
// Let's just throw it, the test framework will register it as a fail.
throw e;
}
// If we get here, the exception was NOT thrown, and that's bad, so..
Assert.fail("Expected exception " + expected + " but didn't see it.");
}

既然你知道了它是如何工作的,你就可以自己写它,从而在正确的地方添加、更改、记录或任何你想在这个过程中做的事情。然而,如果你知道它是IOException,而不是instanceof检查,你可以只检查catch (IOException e),更简单。

最新更新