vendredi 9 septembre 2016

Mockito MissingMethodInvocation - Mocking call method on object that has not been initialized

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.

Aucun commentaire:

Enregistrer un commentaire