weixin_42406059 2011-06-09 16:05
浏览 510
已采纳

如何测试私有方法抛出异常的情况

比如有如下方法:
[code="java"]
private Response getResponse(Request request) throws XXXException
{
if (request == null)
{
throw new XXXException();
}
//To Do
}
[/code]

如果要使用jUnit测试这种抛出异常的情况,应该怎么写?

  • 写回答

2条回答 默认 最新

  • 也许世界还没停 2011-06-09 17:04
    关注

    [code="java"] YourClazz instance = new YourClazz();
    Method method = instance.getClass().getDeclaredMethod("getResponse",
    Request.class);
    method.setAccessible(true);
    try {
    method.invoke(instance, new Object[] { null });
    Assert.assertTrue(false);
    } catch (Exception e) {
    if(e.getCause() instanceof XXXException){
    Assert.assertTrue(true);
    return;
    }
    e.getCause().printStackTrace();
    }
    Assert.assertTrue(false);[/code]
    可以使用反射

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?