美国上市公司,专注Java培训21年

异常处理:实现JUnit API-java培训班


java培训班偶然发现JUnit的GitHub上issue编号#706问题(译注:为JUnit增加一个新API),想到了一个新的处理方法:

ExpectedException#expect(Throwable, Callable)

一方面,建议可以像这样创建一个拦截器。

assertEquals(Exception.class, thrown(() -> foo()).getClass());

assertEquals("yikes!", thrown(() -> foo()).getMessage());

另一方面,为什么不像下面这样这样重新?

// This is needed to allow for throwing Throwables

// from lambda expressions

@FunctionalInterface

interface ThrowableRunnable {

void run() throws Throwable;

}

// Assert a Throwable type

static void assertThrows(

Class throwable,

ThrowableRunnable runnable

) {

assertThrows(throwable, runnable, t -> {});

}

// Assert a Throwable type and implement more

// assertions in a consumer

static void assertThrows(

Class throwable,

ThrowableRunnable runnable,

Consumer exceptionConsumer

) {

boolean fail = false;

try {

runnable.run();

fail = true;

}

catch (Throwable t) {

if (!throwable.isInstance(t))

Assert.fail("Bad exception type");

exceptionConsumer.accept(t);

}

if (fail)

Assert.fail("No exception was thrown");

}

因为大部分功能接口不能抛出Checked异常,所以上面的方法断言:从具体的Runnable-ThrowableRunnable抛出的相应Throwable。

现在我们按照上面想象的JUnit API进行:

assertThrows(Exception.class, () -> { throw new Exception(); });

assertThrows(Exception.class,

() -> { throw new Exception("Message"); },

e -> assertEquals("Message", e.getMessage()));

事实上,甚至我们可以更进一步写出类似下面的帮助方法:

// This essentially swallows exceptions

static void withExceptions(

ThrowableRunnable runnable

) {

withExceptions(runnable, t -> {});

}

// This delegates exception handling to a consumer

static void withExceptions(

ThrowableRunnable runnable,

Consumer exceptionConsumer

) {

try {

runnable.run();

}

catch (Throwable t) {

exceptionConsumer.accept(t);

}

}

这样处理各种异常非常有用。下面是两种常用方法:

try {

// This will fail

assertThrows(SQLException.class, () -> { throw new Exception(); });

}

catch (Throwable t) {

t.printStackTrace();

}

withExceptions(

// This will fail

() -> assertThrows(SQLException.class, () -> { throw new Exception();}),

t -> t.printStackTrace()

);

由于这些方法对很多异常类型和try-with-resources支持不够好,不见得比常用的try..catch..finally语句块有用。

但是这样的方法以后会在日常中用到。


【免责声明】本文部分系转载,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,如涉及作品内容、版权和其它问题,请在30日内与我们联系,我们会予以重改或删除相关文章,以保证您的权益!

Java开发高端课程免费试学

大咖讲师+项目实战全面提升你的职场竞争力

  • 海量实战教程
  • 1V1答疑解惑
  • 行业动态分析
  • 大神学习路径图

相关推荐

更多

Java开班时间

收起