我希望我的junit测试覆盖率包括来自接口的默认方法。下面是来自接口的方法
public default String getServerAddress() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (Exception e) {
return null;
}
}
我的目标是覆盖这个方法的异常部分。所以我可能需要模拟InetAddress来使它抛出异常。但我不知道怎么做?我尝试模仿inetAddress并执行以下操作,但似乎不起作用:
when(inetAddress.getLocalHost().getHostAddress()).thenThrow(Exception.class)
2条答案
按热度按时间sy5wg1nm1#
你可以试试这样的东西:
i7uaboj42#
即使使用Mockito(从3.4.0开始),也可以模拟静态方法。参见文档或tutorial。
另一种可能性是将静态调用 Package 到您自己的类中,并将其注入到最终使用位置。你的 Package 器对象可以用标准的方式被模仿。