简体   繁体   English

如何使用ArgumentCaptor Mockito捕获作为函数的参数

[英]How to capture arguments which are functions using ArgumentCaptor mockito

I have 我有

Somefun(){

   mockedService.execute(()->{
      //function body
   })

}

So I want to run the execute the the method inside the mock. 所以我想在模拟中运行execute方法。 How can I do so? 我该怎么办? I figured out that somehow if I capture the arguments of this mock (which is a function) and execute it, my work would be done. 我发现如果以某种方式捕获该模拟(它是一个函数)的参数并执行它,我的工作就可以完成。 Is there any way to achieve this? 有什么办法可以做到这一点? Or some other way. 或其他方式。 Thanks! 谢谢!

It would look something like this: 它看起来像这样:

@RunWith(MockitoRunner.class)
public class SomeFunTest {
    @Mock Service mockedService;
    @Captor ArgumentCaptor<Runnable /* or whatever type of function you expect there*/> functionCaptor;

    @Test
    public void serviceShouldInvokeFunction() {
        // given
        ObjectUnderTest out = new ObjectUnderTest(mockedService);

        // when
        out.SomeFun();

        // then
        verify(mockedService).execute(captor.capture());

        /* Do your assertions after you captured the value */
        assertThat(captor.getValue()).isInstanceOf(Runnable.class); 
    }
}

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

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