0

我需要断言这CustomException是从私有实用程序方法之一抛出的doSomething

这是我迄今为止实施的并且正在工作。

在测试类级别定义规则

@Rule public ExpectedException exception = ExpectedException.none();

测试方法的相关部分

exception.expect(CustomException.class);
// prepare call to executePrivateMethod
try {
        executePrivateMethod(objInstance, "doSomething",
                arg0, arg1);
    } catch (InvocationTargetException e) {
        Assert.assertTrue("Invalid exception thrown",
                (e.getCause() instanceof CustomException));
        throw (CustomException) e.getCause();
    }

    Assert.fail("Invalid response");


我想知道是否有/是否有替代/优雅的方式可以实现这一目标?

PS:
1.非常有用的帖子,但没有提到我的场景
2.executePrivateMethod使用反射调用私有方法

4

1 回答 1

1

当您需要在抛出异常时进行额外验证时,您的设计是典型的。我要做的唯一评论是您不需要fail,exception.expect会为您处理。

此外,您不需要也不应该强制转换为CustomException. 这可能会导致一个ClassCastException而不是很好的错误消息说明expected CustomException, received SomeOtherException

于 2013-06-26T15:00:48.330 回答