Search code examples
javamockitotestng

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. 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!


Solution

  • 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(functionCaptor.capture());
    
            /* Do your assertions after you captured the value */
            assertThat(functionCaptor.getValue()).isInstanceOf(Runnable.class); 
        }
    }