我有一个集成测试,我调用的方法之一有时会抛出异常。我想忽略这个例外,但我想以最优雅的方式去做。
起初我是这样做的:
// 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);在浏览堆栈溢出时,我注意到in this answer可以这样重写代码:
// 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; }问题:
这似乎是一个足够普遍的代码,我应该能够使用别人的。不想重新发明车轮。
发布于 2017-03-09 08:57:23
使用内置特性的最简单方法,我可以想出
new FutureTask<>(() -> coffee.spill()).run();FutureTask不会忽略异常,但会捕获并记录异常,所以仍然需要您决定不查询结果。
如果spill()已被声明为void,则不能将其用作简单的Callable,因此您必须使用
new FutureTask<>(() -> { coffee.spill(); return null; }).run();但值得商榷的是,基于lambda表达式的解决方案是否可以简化原始代码,但由于换行导致代码看起来不那么简洁:
try{ coffee.spill(); } catch(Exception e){}
ignoreExceptions(() -> coffee.spill());// saved four chars...https://stackoverflow.com/questions/42684176
复制相似问题