Mockito MissingMethodInvocationException

时间:2016-04-26 12:46:53

标签: java elasticsearch junit mockito

我知道有很多问题/答案与我的问题相似,但我仍然无法通过测试解决这个问题。

问题: 我试图模仿Settings类,但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();
 }
}

1 个答案:

答案 0 :(得分:2)

settings是你的模仿,如果你调用它,你可以告诉Mockito要返回什么。

然而,

settings.settingsBuilder()并没有返回模拟,这就是Mockito所抱怨的。当<{1}}被调用时,你可以告诉Mockito返回一个模拟对象,例如。

settingsBuilder

如果你没有另外声明,你的mock将默认为对象引用返回null,注意。