I have the below conditional statement which I need to mock. Is it possible to mock this using mockito?
if (events.size() == rowsAffected) {
// app logic
}
Here the events
are of type List<Map<String, Object>>
which will be returned from a function.
rowsAffected
is of type int
which will also be returned by a method.
List<Map<String, Object>> events = service.getEvents();
int rowsAffected = service.updateEventStatus(events);
When you need to mock a method with custom behavior, you can use answer
. Example:
public class MockMe {
public String hello(String name) {
return "Hello " + name;
}
}
@Test
public void testCase() {
List<Map<String, Object>> events = service.getEvents();
int rowsAffected = service.updateEventStatus(events);
Answer<String> myMockedAnswer = invocation -> {
if (events.size() == rowsAffected) {
return "mock good";
}
return "mock bad";
};
MockMe mockMe = mock(mockMe);
doAnswer(myMockedAnswer)
.when(mockMe).hello(anyString());
assertEquals("mock good", mockMe.hello("anything"));
}
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.