如何使用 ArgumentCaptor mockito 捕获作为函数的参数 [英] How to capture arguments which are functions using ArgumentCaptor mockito

查看:192
本文介绍了如何使用 ArgumentCaptor mockito 捕获作为函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

Somefun(){

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

}

所以我想在模拟中运行 execute 方法.我怎么能这样做?我发现如果我以某种方式捕获这个模拟(这是一个函数)的参数并执行它,我的工作就会完成.有没有办法实现这一目标?或者其他方式.谢谢!

So I want to run the execute the the method inside the mock. 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!

推荐答案

它看起来像这样:

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

这篇关于如何使用 ArgumentCaptor mockito 捕获作为函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆