简体   繁体   English

使用模拟方法参数模拟后续步骤

[英]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). 我希望能够模拟它(使用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 . 意思是,我想调用发送给方法onResult的参数的handle方法。 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: 好的,未测试,但是在这种情况下可以使用ArgumentCaptor

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. 但是,不确定捕获者是否具有在此处初始化的“时间”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM