1 回答

TA貢獻1804條經(jīng)驗 獲得超7個贊
我嘗試了您的代碼,它按您的預期工作。我創(chuàng)建了被測方法,例如:
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());
}
}
添加回答
舉報