Mockito is a mock framework which you can use to write simple and clean tests. One of it’s nice features is the ArgumentMatcher. With the ArgumentMatcher you can determine the outcome of your mocked service or repository based on any condition you want. Imagine we have a CandyService which can get a list of candies which are liked by a specific customer. This service uses the external ChocalateService which specifically checks if the customer likes chocolate. The CandyServiceTest class looks like this:

@RunWith(MockitoJUnitRunner.class) // will initiate and inject the mocks

public class CandyServiceTest {

    @Mock
    private ChocolateService chocolateService;

    @InjectMocks
    private CandyService candyService = new CandyServiceImpl();

    @Test
    public void testCustomerLikesChocolate() throws ParseException {
        Customer customer = new Customer();
        customer.setFirstName("Albert");
        List candiesLikedByCustomer = candyService.getCandiesLikeByCustomer(customer);
        assertTrue(candiesLikedByCustomer.contains(Candy.CHOCOLATE), "Expected customer to like chocolate");

    }

    @Test
    public void testCustomerWhoNotLikesChocolate() throws ParseException {
        Customer customer = new Customer();
        customer.setFirstName("Any other firstname");
        List candiesLikedByCustomer = candyService.getCandiesLikedByCustomer(customer);
        assertFalse(candiesLikedByCustomer.contains(Candy.CHOCOLATE), "Expected customer not to like chocolate");

    }
}

In our first test we expect the CandyService to return a list which includes Chocolate. Therefore the mocked ChocolateService should return true. For this test we will let the service return true if the firstname of the customer is “Albert”. Therefore we need to create the ArgumentMatcher. Since the ArgumentMatcher is an interface, we create a private class in our test as shown below:

private class customersWhoLikesChocolate extends ArgumentMatcher {
        public boolean matches(Object object) {

            Customer customer = (Customer) object;
            if (customer == null || customer.getFirstName() == null) {
                return false;
            }
            return customer.getFirstName().equals("Albert");
        }
    }

Finally in our @Before method we setup the mocked ChocolateService to return true if the argument of its method matches to our ‘customersWhoLikesChocolate’ ArgumentMatcher.

@Before
    public void before() {
        Customer customersWhoLikesChocolate = argThat(new CustomersWhoLikesChocolate());
        when(chocolateService.doesCustomerLikesChocolate(customersWhoLikesChocolate)).thenReturn(true);

    }

Another handy feature of Mockito is the ArgumentCaptor. More information about the ArgumentMatcher can be found in the Mockito API or take a look at the mockito site: http://www.mockito.org.

shadow-left