1 回答
TA贡献1804条经验 获得超7个赞
我尝试了您的代码,它按您的预期工作。我创建了被测方法,例如:
public String printHostname() throws Exception {
return InetAddress.getLocalHost().getHostName();
}
和测试类:
@RunWith(PowerMockRunner.class)
public class ClassUnderTestTest {
@PrepareForTest({InetAddress.class, ClassUnderTest.class})
@Test
public void testFunc() throws Exception {
final ClassUnderTest classUnderTest = new ClassUnderTest();
PowerMockito.mockStatic(InetAddress.class);
final InetAddress inetAddress = PowerMockito.mock(InetAddress.class);
PowerMockito.doReturn("testHost", "anotherHost")
.when(inetAddress, PowerMockito.method(InetAddress.class, "getHostName"))
.withNoArguments();
PowerMockito.doReturn(inetAddress).when(InetAddress.class);
InetAddress.getLocalHost();
Assert.assertEquals("testHost", classUnderTest.printHostname());
Assert.assertEquals("anotherHost", classUnderTest.printHostname());
}
}
添加回答
举报