mardi 22 mai 2018

Junit - Mockito - how to setUp mocked objects properly

I'm creating tests for different methods, but all these methods are pretty similar - adding something to Day.. I have created Day object for test, and I have mocked some things such as DataBase that Day is using. But I have problems with setup this properly. For example one method that return Day to use this Day in my addSomething method has thing like this:

Item item = dbService.get(tableName, Collections.singletonList(primaryKey));
String measurementsJSON = item.getJSON("measurements");

I've mocked DB and Item and I wanted to setup 'before' things so I did this:

@Before
public void setUp() throws Exception {
    activitiesService = new ActivitiesService(databaseControllerMock);
    when(eq(item).getJSON(anyString())).thenReturn(anyString());
}

But in this case I'm getting error:

java.lang.NullPointerException
at service.activity.service.ActivitiesServiceTest.setUp(ActivitiesServiceTest.java:45) //this line with "when..."

And other errors:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced argument matcher detected here:
-> at service.activity.service.ActivitiesServiceTest.setUp(ActivitiesServiceTest.java:45)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().

Can someone help me with this?

Aucun commentaire:

Enregistrer un commentaire