Reputation: 1292
I have a code where I need to pass any mock object instance of some type to a method and want the same mock instance to set some values in return.
As this is a void method, I am using doAnswer
to set some values for the passed in argument. In this case the argument is mocked object.
Now the question is, is there a way can I set the value to the mocked object and use the same instance to assert for something?
I tried with doAnswer
for the void
method. Is there any other way to achieve this?
doAnswer(new Answer() {
ManageKit manageKit = new ManageKit();
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length == 1 && arguments[0] != null ) {
manageKit = (ManageKit)arguments[0];
manageKit.setStudySchemaEventId(12);
}
return manageKit;
}
}).when(mockManageKitsDao).retrieveInterventionEventId(any(ManageKit.class), any(Connection.class));
TileInfo tileInfo = doubleBliService.getTileInfo(9500, 5);
assertThat(manageKit.getStudySchemaEventId()).isEqualTo(12);
I cannot pass ManageKit
object directly as it is creating object inside the method. something like below:
public TileInfo getTileInfo(int studyId, int caseDetailId) {
.......
........
ManageKit manageKit = new ManageKit();
manageKit.setCaseDetailId(caseDetailId);
manageKitsDao.retrieveInterventionEventId(manageKit, connection);
int armStudySchemaEventId = 0;
if (manageKit.getStudySchemaEventId() != null && manageKit.getStudySchemaEventId() != 0) {
armStudySchemaEventId = manageKit.getStudySchemaEventId();
}
Upvotes: 0
Views: 414
Reputation: 3511
Mockito provide a mechanism to for acquiring an instance of an abject passed into a mocked method: ArgumentCaptor.
In your particular case (schematically):
// configure
doAnswer(answer).when(mockManageKitsDao).retrieveInterventionEventId(any(ManageKit.class), any(Connection.class));
// act
TileInfo tileInfo = doubleBliService.getTileInfo(9500, 5);
// verify
ArgumentCaptor<ManageKit> argumentCaptor = ArgumentCaptor.forClass(ManageKit.class);
verify(mockManageKitsDao).retrieveInterventionEventId(argumentCaptor.capture(), any(Connection.class));
ManageKit manageKit = argumentCaptor.getValue();
assertThat(manageKit.getStudySchemaEventId()).isEqualTo(12);
Upvotes: 1