2017-04-21 57 views

回答

1

你給的鏈接方法等效於以下內容:

InetAddress localHost = InetAddress.getLocalhost(); 
String hostName = localHost.getHostName(); 

因此,我們需要分成兩個嘲笑這一點。

@Test 
public void myTest(@Mocked InetAddress mockedLocalHost) throws Exception { 

    new Expectations() {{ 
     mockedLocalHost.getHostName(); 
     result = "mockedHostName"; 
    }}; 

    // More to the test 
} 

但是,我們如何讓mockedLocalHost是當我們調用InetAddress.getLocalhost()時返回的實例:

第二部分是容易被剛剛嘲笑一個InetAddress並把它在一個Expectations塊像這樣做呢?用partial mocking,可以用於任何靜態方法。對於語法是包括含有靜態方法爲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()爲你的計劃。

相關問題