[英]how to return “localhost” from InetAddress.getLocalHost().getHostName() in docker container
[英]how to mock inetaddress.getlocalhost().gethostname() to throw an exception
我希望我的 junit 测试覆盖率包括来自接口的默认方法。 以下是接口中的方法
public default String getServerAddress() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (Exception e) {
return null;
}
}
我的目标是覆盖此方法的异常部分。 所以我可能需要模拟 .netAddress 以使其抛出异常。 但我不确定如何? 我试图模拟 .netAddress 并执行以下操作,但似乎没有用:
when(inetAddress.getLocalHost().getHostAddress()).thenThrow(Exception.class)
你可以尝试这样的事情:
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
@RunWith( PowerMockRunner.class )
@PrepareForTest( NetworkReader.class )
public class Tests {
@Test
public void testGetServerAddress() {
mockStatic(NetworkUtil.class);
when(NetworkReader.getLocalHostname()).thenThrow(new Exception("exception message));
// Here you could test your interface.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.