在Java8中寻找内置函数以忽略异常
我有一个集成测试,其中我调用的一个方法有时会抛出异常。我想忽略这个例外,但我想用最优雅的方式来做 最初我是这样做的:在Java8中寻找内置函数以忽略异常,java,exception,lambda,java-8,Java,Exception,Lambda,Java 8,我有一个集成测试,其中我调用的一个方法有时会抛出异常。我想忽略这个例外,但我想用最优雅的方式来做 最初我是这样做的: // GIVEN NewsPaper newspaper = new NewsPaper(); Coffee coffee = new Coffee(); // WHEN try{ coffee.spill() }catch(Exception e){ // Ignore this exception. I don't care what coffee.spi
// GIVEN
NewsPaper newspaper = new NewsPaper();
Coffee coffee = new Coffee();
// WHEN
try{
coffee.spill()
}catch(Exception e){
// Ignore this exception. I don't care what coffee.spill
// does as long as it doesn't corrupt my newspaper
}
// THEN
Assert.assertTrue(newspaper.isReadable);
// GIVEN
NewsPaper newspaper = new NewsPaper();
Coffee coffee = new Coffee();
// WHEN
ingoreExceptions(() -> coffee.spill());
// THEN
Assert.assertTrue(newspaper.isReadable);
浏览stackoverflow时,我注意到我可以像这样重写代码:
// GIVEN
NewsPaper newspaper = new NewsPaper();
Coffee coffee = new Coffee();
// WHEN
try{
coffee.spill()
}catch(Exception e){
// Ignore this exception. I don't care what coffee.spill
// does as long as it doesn't corrupt my newspaper
}
// THEN
Assert.assertTrue(newspaper.isReadable);
// GIVEN
NewsPaper newspaper = new NewsPaper();
Coffee coffee = new Coffee();
// WHEN
ingoreExceptions(() -> coffee.spill());
// THEN
Assert.assertTrue(newspaper.isReadable);
但是,我需要提供自己的{{ignoringExc}}实现:
public static void ingoreExceptions(RunnableExc r) {
try { r.run(); } catch (Exception e) { }
}
@FunctionalInterface public interface RunnableExc { void run() throws Exception; }
问题:
- Java8是否附带了这样的东西,我可以开箱即用
- 什么实用程序库有这样的功能李>
这似乎是一段足够通用的代码,我应该能够使用其他人的。我不想重新发明轮子 我能想到的使用内置功能的最简单方法是
new FutureTask<>(() -> coffee.spill()).run();
但有争议的是,是否有任何基于lambda表达式的解决方案可以简化原始代码,因为换行符的存在,原始代码看起来不够简洁:
try{ coffee.spill(); } catch(Exception e){}
ignoreExceptions(() -> coffee.spill());// saved four chars...
这是几行,几乎在所有情况下,都是一个糟糕的想法。所以我认为没有JDK内置的异常吞咽器。各种测试工具通常都提供了一些功能,尽管界面很有用,但我同意,除了用于单元测试的库之外,该方法不太可能包含在任何库中。是的,即使在这种情况下,帮助您跳过异常处理的实用程序通常也会以某种方式记录它们。非本地出口会影响您的代码覆盖率,例如,如果您从事这类工作。JUnit和TestNG有一些方法可以预期异常,但这有点不同,因为如果您没有获得异常,测试将失败。