1

I have a following class:

public class Task {

    public <V> V run(Callable<V> callable) {
        //...
        callable.call()
    }
}

And I have a class that uses the above:

public MyClass {
    Task task;
    Provider provider;

    public void doYourJob() {
           String parameter = "Test";
           task.run(() -> provider.save(parameter)); 
    }

}

I need to now write unit test to this piece, so that it checks if I actually called provider with proper parameters.

I tried approach with argumentCaptors:

@ExtendWith(MockitoExtension.class)
class MyClassTest {
    @Mock
    Task task;

    @Mock
    Provider provider;

    MyClass myClass;

    @Captor
    ArgumentCaptor<Callable<String>> captor;

    @BeforeEach
    public void setup()
        myClass = new MyClass(task, provider);
    }
        
    @Test
    void shouldDoJob() {
        myClass.doYourJob();
        verify(task).run(captor.capture());
        captor.call();
        verify(provider).save("Test");
    }
}

This fails with error: Wanted but not invoked: task.run(<Capturing argument)); There was an interaction with this mock: task.run(MyClass$$Lambda$$598dsfg897);

Also I tried approach with mocking and with doAnswer - in all cases Callable parameter was interpreted wrong.

Any clues how to mock Callable and check what was actually called?

Tirlipirli
  • 103
  • 2
  • 10
  • 1
    Why is it/you think `Callable`? It looks rather like `Callable` – xerx593 Oct 25 '22 at 13:58
  • This is just an example. In real code, I am using this task.run method with various calls to various methods, parameters differ. – Tirlipirli Oct 25 '22 at 14:12
  • I've marked this as a duplicate that discusses verification in particular, but the dupe answer also mentions [capturing using captors](https://stackoverflow.com/q/34807210/1426891). If these aren't applicable your case, please edit your question to explain the difference and I can reopen. – Jeff Bowman Oct 25 '22 at 20:37
  • Similar, except that solution provided there is exactly the one that I tried - and get mentioned exception – Tirlipirli Oct 26 '22 at 06:38
  • 2
    @xerx593 - thank you for your comment! It pointed me to the right direction. Problem was that in fact, I wasn't calling Callable method, but similar one, also defined, taking Runnable as parameter and then in my test I needed to mock Runnable version instead of Callable. And when I changed Captor to ArgumentCaptor, all started to work. And therefore this question is a duplicate as marked. – Tirlipirli Oct 26 '22 at 14:04

0 Answers0