为了账号安全,请及时绑定邮箱和手机立即绑定

如何在对模拟静态方法的顺序调用中返回多个答案

如何在对模拟静态方法的顺序调用中返回多个答案

30秒到达战场 2022-10-07 19:40:07
我有一个返回值的函数 java.net.InetAddress.getLocalHost().getHostName()我已经为我的函数编写了一个测试,如下所示:@PrepareForTest({InetAddress.class, ClassUnderTest.class})@Testpublic void testFunc() throws Exception, UnknownHostException {  final ClassUnderTest classUnderTest = new ClassUnderTest();  PowerMockito.mockStatic(InetAddress.class);   final InetAddress inetAddress = PowerMockito.mock(InetAddress.class);  PowerMockito.doReturn("testHost", "anotherHost").when(inetAddress, method(InetAddress.class, "getHostName")).withNoArguments();  PowerMockito.doReturn(inetAddress).when(InetAddress.class);  InetAddress.getLocalHost();  Assert.assertEquals("testHost", classUnderTest.printHostname());  Assert.assertEquals("anotherHost", classUnderTest.printHostname());  }printHostName简直就是return java.net.InetAddress.getLocalHost().getHostName();我将如何调用getHostName返回anotherHost第二个断言?我试过做:((PowerMockitoStubber)PowerMockito.doReturn("testHost", "anotherHost")).when(inetAddress, method(InetAddress.class, "getHostName")).withNoArguments();PowerMockito.doReturn("testHost", "anotherHost").when(inetAddress, method(InetAddress.class, "getHostName")).withNoArguments();我在这里尝试使用doAnswer解决方案:Using Mockito with multiple calls to the same method with the same arguments但没有效果,因为testHost两次仍然返回。
查看完整描述

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());

    }


}


查看完整回答
反对 回复 2022-10-07
  • 1 回答
  • 0 关注
  • 63 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信