Mockito MissingMethodInvocationException
14,763
settings
is your mock, and you can tell Mockito what to return if you invoke on it.
settings.settingsBuilder()
does not return a mock, however, and that's what Mockito is complaining about. You can tell Mockito to return a mocked object when settingsBuilder
is invoked e.g.
Builder settingsBuilder = mock(Builder.class);
when(settingsBuilder.doX()).thenReturn(...);
when(settings.settingsBuilder()).thenReturn(settingsBuilder);
Your mock will return null by default for an object reference if you don't declare otherwise, note.
Author by
Bob
Updated on June 07, 2022Comments
-
Bob almost 2 years
I am aware that there is a number of questions/answers similar for my question but I am still unable to resolve this issue with my testings.
Problem: I am trying to mock the Settings class but Mockito complains about this line:
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.
I've tried a number of possible ways but no results. Bellow is the actual testing method.
@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(); } }