断言从java中的私有方法抛出异常的替代方法

时间:2013-06-26 13:21:46

标签: java exception reflection junit

我需要声明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");


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

P.S。:
1。非常有帮助post但没有提到我的情景
2。 executePrivateMethod使用反射来调用私有方法

1 个答案:

答案 0 :(得分:0)

当您在抛出异常时需要执行其他验证时,您的设计是典型的。我唯一的评论是你不需要failexception.expect为你照顾。

此外,您不需要也不应该转换为CustomException。这可能会导致ClassCastException而不是声明expected CustomException, received SomeOtherException的错误消息。