简体   繁体   中英

Using mocked method argument to mock next steps

I have a method in my code that looks something like this:

action.onResult(new Handler<MyClass>() {
        @Override
        public MyClass handle() { // Do something here }
     }
}

I want to be able to mock it (using Mockito). Something like this:

when(mockedAction.onResult(any(Handler.class))).thenReturn(firstArg.handle());

Meaning, I want to call the handle method of the argument that's sent to the method onResult . I can't mock the handler because it uses inner methods of the calling class (I thought about using a private class but haven't reached a good enough solution)

Motivation : This is an asynchronous callback mechanism that's used in a synchronous area. I want to mock the call to the handler itself in order to continue the flow synchronously in the code.

OK, UNTESTED but here is a possible use of ArgumentCaptor for this scenario:

final ArgumentCaptor<Handler> captor = ArgumentCaptor.forClass(Handler.class);

when(mock.onResult(captor.capture())).thenReturn(captor.getValue().handle());

Not sure however whether the captor has the "time" to initialize here.

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