Question

This is my sample service class:

class Service {

    @Inject
    private TestDao dao;

    public void method() {
        //Other logic
        List<SomeClass> list = new ArrayList<SomeClass>();
        privateMethod(list);
        //Other logic
    }

    private void privateMethod(List<SomeClass> list) {
        dao.save(list);
    }
}

If I mock dao using Mockito, then how can I test the number of calls to dao.save method? When I tried with verify, I have to give the list object. But I am not seeing any way to get that object.

Any thoughts?

Was it helpful?

Solution

You can use the anyList() matcher if you don't care about exactly what list your method is being called with. For example, if you want to verify the save() method was called exactly thrice:

verify(dao, times(3)).save(anyList())

If you want to make further assertions about what list save() was called with, use ArgumentCaptor

An example usage of ArgumentCaptor:

ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(dao, times(3)).save(argument.capture());
List secondValue = argument.getAllValues().get(1); // captured value when the method was called the second time

OTHER TIPS

Call verify with Matchers.anyList():

verify(dao).save(Matchers.anyList());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top