Wednesday, 31 July 2013

Mockito: Using ArgumentCaptor to capture argument values for further assertions.

Sometimes there are situations where I need to assert the arguments that are passed into a service, but that arguments are instantiated within a method that you want to test and in which case it cannot be asserted using a plain JUnit test.

With Mockito, I can use the ArgumentCaptor to captures values and assert them.

To explain this better, consider the following simple scenario in the CarSelector.java class.
In this class, I want to verify that every time the method buyRedFerrari() is invoked, which subsequently invoked the service (CarBuilderService.buildCar) method to build a car, it passes the expected instance of BuyingCriteria.
In this case, when the CarBuilderService.buildCar is called, it is passed with the argument that the car has to be RED and the model is a FERRARI.

Usage examples:
package org.drage.tutorial.mocking;
public class CarSelector {
private final CarBuilderService service;
public CarSelector(CarBuilderService service) {
this.service = service;
}
public void buyRedFerrari(){
BuyingCriteria criteria = new BuyingCriteria();
criteria.setColor("RED");
criteria.setModel("FERRARI");
service.buildCar(criteria);
}
public void buyPinkCaddilac(){
BuyingCriteria criteria = new BuyingCriteria();
criteria.setColor("HOT PINK");
criteria.setModel("CADDILAC");
service.buildCar(criteria);
}
}
package org.drage.tutorial.mocking;
// imports ...
@RunWith(MockitoJUnitRunner.class)
public class CarSelectorTest {
private CarSelector carSelector;
@Mock
private CarBuilderService service;
@Before
public void initTest(){
carSelector = new CarSelector(service);
}
@Test
public void testBuyRedFerrari() {
carSelector.buyRedFerrari();
ArgumentCaptor<BuyingCriteria> argumentCaptor = ArgumentCaptor.forClass(BuyingCriteria.class);
Mockito.verify(service).buildCar(argumentCaptor.capture());
BuyingCriteria buyingCriteria = argumentCaptor.getValue();
assertEquals("RED", buyingCriteria.getColor());
assertEquals("FERRARI", buyingCriteria.getModel());
}
}
package org.drage.tutorial.mocking;
public interface CarBuilderService {
void buildCar(BuyingCriteria criteria);
}
package org.drage.tutorial.mocking;
public class BuyingCriteria {
private String color;
private String model;
// getters and setters
}


References:
Mockito
ArgumentCaptor API

No comments:

Post a Comment