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:


References:
Mockito
ArgumentCaptor API

No comments:

Post a Comment