简体   繁体   中英

How to mock a void method which takes mock object and expect to set some value for mock object instance

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();
}

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);

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