[英]How do I mock static chained methods using jmockit in Java
InetAddress.getLocalHost().getHostName()
如何利用JMockit来测试上面的代码?
您提供的链式方法等效于以下内容:
InetAddress localHost = InetAddress.getLocalhost();
String hostName = localHost.getHostName();
因此,我们需要将其分解为两个嘲讽。
第二部分很容易通过模拟InetAddress
并将其放在Expectations
块中来完成:
@Test
public void myTest(@Mocked InetAddress mockedLocalHost) throws Exception {
new Expectations() {{
mockedLocalHost.getHostName();
result = "mockedHostName";
}};
// More to the test
}
但是我们如何让mockedLocalHost
成为我们调用InetAddress.getLocalhost()
时返回的实例? 使用部分模拟 ,可用于任何静态方法。 其语法是将包含静态方法的类作为new Expecations()
的参数包含new Expecations()
,然后像其他任何方法调用一样模拟它:
@Test
public void myTest(@Mocked InetAddress mockedLocalHost) throws Exception {
new Expectations(InetAddress.class) {{
InetAddress.getLocalHost();
result = mockedLocalHost;
mockedLocalHost.getHostName();
result = "mockedHostName";
}};
// More to the test
}
这将导致按计划InetAddress.getLocalHost().getHostName()
。
声明@Mocked InetAddress var1
就足够了。 默认情况下, @Mocked
类型的所有方法(包括静态方法)都返回@Mocked
。 然后, Expectations
中唯一的被存根(“记录”)的调用是那些对于被测试的代码或要验证的代码具有重要结果的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.