Reputation: 2585
I have the following code which I want to test:
pojo.setStatus(Status.INITIAL);
pojo.setExecutionCounter(0);
//eventRepository is a mock
scheduleEvent(this.eventRepository.save(pojo).get());
In a unit test, I'd like to verify that
INITIAL
and the counter is 0
Unfortunately, I have no clue how to do that, since I have to return the argument which I have to capture
. Maybe it's getting more clear when I show the example of my unit test:
succeededEvent.setEventStatus(INITIAL);
succeededEvent.setExecutionCounter(0);
//Actually we want here to return the argument
//which is captured by eventArgumentCaptor??
when(this.eventRepository.save(this.eventArgumentCaptor.capture()))
.thenReturn(succededEvent);
this.processor.processEvent(initialEvent);
Mockito.verify(this.eventRepository,
Mockito.times(1)).save(eventCaptureExecuteCaptor.capture());
final Event capturedEvent = eventCaptureExecuteCaptor.getValue();
//Counter and status should be reset
assertEquals(new Integer(0), capturedEvent.getExecutionCounter());
assertEquals(INITIAL, capturedEvent.getEventStatus());
verify(this.eventRepository,
times(1)).save(eq(eventCaptureExecuteCaptor.getValue()));
Upvotes: 0
Views: 1101
Reputation: 26522
Not sure why you need to use captor while stubbing. You use it, as designed, after the invocation of the SUT:
this.processor.processEvent(initialEvent);
Mockito.verify(this.eventRepository,
Mockito.times(1)).save(eventCaptureExecuteCaptor.capture());
While stubbing, you can directly go for the concrete object that is expected:
when(this.eventRepository.save(succededEvent)
.thenReturn(succededEvent);
or use a generic input if you do not have that object at hand on set-up:
when(this.eventRepository.save(anyClass(EventPojo.class))
.thenReturn(succededEvent);
Edit:
You can also use the thenAnswer
along with accepting any input class of Pojo type:
when(this.eventRepository.save(Mockito.any(EventPojo.class))
.thenAnswer(new Answer<EventPojo>(){
EventPojo pojo = invocation.getArgument(0);
return pojo;
}
);
as this is an anonymous implementation, you can catch the state of the passed pojo if you have the need.
Upvotes: 1