Verify a method was called with certain argument using Mockito

Unit test are important part of every application. Even though we sometimes hate to write time and think they are just time consuming, they can make our app must more stable and bulletproof. One often scenario that we want to test is to check if some method in a class was called with certain parameters. We have a class Importer to read and import a record from XML.

We want to test if XML was correctly read and if our process(record) method was called with record object.

Solution

ArgumentCaptur enables us to capture actual object that is passed to our process(record) method. We don’t only test if method was called, but also if it was called with specific values.

Extra tip for collections

Again, let’s image we modify our method to be able to read multiple records.

Solution is similar. To test collection (List, Set, Map…) arguments, we have to use some additional Mockito features.

In our test, recordsCaptor.getValue() returns Set. We can check size or each record. So with Mockito you can test a lot of scenarios and it’s a really nice tool for unit testing.