2016-04-26 49 views
0

我知道有很多問題/答案類似於我的問題,但我仍然無法使用我的測試來解決此問題。Mockito MissingMethodInvocationException

問題: 我試圖嘲弄設置類,但抱怨的Mockito這個行:

when(settings.settingsBuilder().put(new String("test"), "test").build()).thenReturn(settings) 

MissiongMethodInvocationException:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'. 
For example: 
when(mock.getArticles()).thenReturn(articles); 

Also, this error might show up because: 
1. you stub either of: final/private/equals()/hashCode() methods. 
Those methods *cannot* be stubbed/verified. 
Mocking methods declared on non-public parent classes is not supported. 
2. inside when() you don't call method on mock but on some other object. 

我已經嘗試了多種可能的方式,但沒有結果。波紋管是實際的測試方法。

@RunWith(PowerMockRunner.class) 
@PrepareForTest({Settings.class, Client.class}) 
public class AddressMatcherElasticTest { 

private final AddressWebConfiguration configuration = mock(AddressWebConfiguration.class); 
private final Settings settings = mock(Settings.class); 
private final Client client = mock(Client.class); 

    @Test 
    public void match() throws Exception { 
    when(configuration.getClusterName()).thenReturn(new String("name")); 
    when(settings.settingsBuilder().put(new String("name"), "test").build()).thenReturn(settings); 
    AddressMatcherElastic test = new AddressMatcherElastic(configuration); 
    verify(configuration, times(1)).getClusterName(); 
} 
} 

回答

2

settings是你的模擬,你可以告訴如果的Mockito調用它什麼返回。

settings.settingsBuilder()不會返回一個模擬,但是,這正是Mockito抱怨​​的。您可以在調用settingsBuilder時告訴Mockito返回模擬對象。

Builder settingsBuilder = mock(Builder.class); 
when(settingsBuilder.doX()).thenReturn(...); 
when(settings.settingsBuilder()).thenReturn(settingsBuilder); 

如果你沒有另外聲明,你的模擬將默認返回null對象引用。

+0

感謝Brian,它的工作。 – Bob