第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在對模擬靜態(tài)方法的順序調(diào)用中返回多個答案

如何在對模擬靜態(tài)方法的順序調(diào)用中返回多個答案

30秒到達戰(zhàn)場 2022-10-07 19:40:07
我有一個返回值的函數(shù) java.net.InetAddress.getLocalHost().getHostName()我已經(jīng)為我的函數(shù)編寫了一個測試,如下所示:@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();我將如何調(diào)用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條經(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());

    }


}


查看完整回答
反對 回復 2022-10-07
  • 1 回答
  • 0 關(guān)注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號