简体   繁体   中英

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. But I have problems with setting up this properly.

For example: one method which returns Day to use this Day in my addSomething() method is 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().

As the message says

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);

Change

when(eq(item).getJSON(anyString())).thenReturn(anyString());

to some string return, something like

when(eq(item).getJSON(anyString())).thenReturn("{somekey:somevalue}");

I am assuming you want to return a json representation as string

You shouldn't use when clause inside setUp method.

@Before
public void setUp() throws Exception {
     activitiesService = new ActivitiesService(databaseControllerMock);
}

@Test
public void testSomething() {
      when(eq(item).getJSON(anyString())).thenReturn(anyString());
}

Besides, if you can add your class to want to test, we can help more easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM