0

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");
  • What type is "obj1" and "obj2"? I believe you should have something like: @Mock private MyThing obj1 Where "MyThing" is your type. – ThePerson Sep 09 '16 at 18:23
  • Could you give a [mcve] rather than pseudo-code? It would help us to reproduce the issue. – Jon Skeet Sep 09 '16 at 18:23
  • My bad I forgot to include the types in the example I posted but they're there. The mock lines have \@Mock private obj1Type obj1; and \@Mock private obj2Type obj2; – David Streid Sep 09 '16 at 18:48

0 Answers0