How to capture arguments which are functions using

2019-08-19 02:27发布

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条回答
何必那么认真
2楼-- · 2019-08-19 02:54

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); 
    }
}
查看更多
登录 后发表回答