JUnit 4 - 期望某个类的异常,但不是子类

dav*_*wil 5 java junit

我会尝试提供一个陈腐,无用的例子,可以很好地减少问题:-)

我有一个GenericException,一个MoreSpecificException延伸GenericException.

我需要测试SomeService.doThis()抛出一个MoreSpecificException.JUnit让我这样优雅地做到这一点.

@Test(expected = MoreSpecificException.class)
public void testDoThis() throws GenericException {
    new SomeService().doThis();
}
Run Code Online (Sandbox Code Playgroud)

但是,我还需要测试那个SomeService.doThat()抛出一个GenericException,所以我尝试了这个.

@Test(expected = GenericException.class)
public void testDoThat() throws GenericException {
    new SomeService().doThat();
}
Run Code Online (Sandbox Code Playgroud)

但是,我发现如果doThat()实际上抛出一个,MoreSpecificException那么第二个测试仍然会通过.我认为这是因为MoreSpecificException 是a GenericException和注释是为了尊重这种关系而实现的.

虽然这是一个合理的默认行为,但我不希望这样.我想测试doThat()抛出一个GenericException而且只有一个GenericException.如果它抛出一个MoreSpecificException或任何其他子类GenericException,我希望测试失败.

阅读文档似乎我不能用注释来改变这种行为,所以看起来我将不得不使用另一种解决方案.

目前我正在采取以下丑陋的解决方案 - 编辑使得Nathan Hughes的回答明显不那么难看 :-)

@Test
public void testDoThat() {
    try {
        new SomeService().doThat();
        Assert.fail();
    } catch(GenericException ex) {
        Assert.assertEquals(GenericException.class, ex.getClass());
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的方式在JUnit框架中实现我想要的东西?

Mar*_*szS 3

BDD风格的解决方案

JUnit 4 +捕获异常+ AssertJ

最优雅的解决方案;)可读,没有样板代码。

@Test
public void testDoThat() {

    when(new SomeService()).doThat();

    then(caughtException()).isExactlyInstanceOf(GenericException.class);

}
Run Code Online (Sandbox Code Playgroud)

FEST Assertions 2 + Catch-Exceptions的代码是相同的。

源代码

依赖关系

org.assertj:assertj-core:1.4.0
com.googlecode.catch-exception:catch-exception:1.2.0
Run Code Online (Sandbox Code Playgroud)