Can someone please provide me with a way to use Mockito to test the following piece of code? I am currently receiving a MissingMethodInvocation Exception.
obj1.getId().getString()
obj1 is a mocked object and the getId() method returns another object, obj2, with a getString() method. I have tried
@Mock private obj1
@Mock private obj2
Mockito.when(obj1.getId()).thenReturn(obj2);
Mockito.when(obj2.getString()).thenReturn("TEST STRING");
However, I receive the following error
<<< ERROR!
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.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
It is a limitation of the mock engine.
And trying
@Mock private obj1
@Mock private obj2
Mockito.when(obj1.getId().getString()).thenReturn("TEST STRING");
returns
<<< ERROR!
java.lang.NullPointerException: null
Thanks in advance for any help or references.
SOLUTION obj2.getString() is a final method, which as the error readout says - "1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified."
My workaround is to set the string of obj2 -
@Mock private Obj1Type obj1
Mockito.when(obj1.getId()).thenReturn(obj2);
obj2.setString("TEST_STRING");