How to capture arguments which are functions using ArgumentCaptor mockito

老子叫甜甜 提交于 2020-01-06 05:57:47

问题


I have

Somefun(){

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

}

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!


回答1:


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


来源:https://stackoverflow.com/questions/47565887/how-to-capture-arguments-which-are-functions-using-argumentcaptor-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!