Use Mockito to mock autowired fields

Dependency injection is very powerful feature of Inversion of Control containers like Spring and EJB. It is always good idea to encapsulate injected values into private fields. But encapsulation of autowired fields decreases testability.

I like the way how Mockito solved this problem  to mock autowired fields. Will explain it on example. (This blog post expects that you are little bit familiar with Mockito syntax, but it is self-descriptive enough though.)

Here is first dependency of testing module. It is Spring singleton bean. This class will be mocked in the test.

public class OrderDao {
	public Order getOrder(int irderId){
		throw new UnsupportedOperationException("Fail is not mocked!");

Here is second dependency of testing class. It is also Spring component. This class will be spied (partially mocked) in test. Its method calculatePriceForOrder will be invoked unchanged. Second method will be stubbed.

public class PriceService {
	public int getActualPrice(Item item){
		throw new UnsupportedOperationException("Fail is not mocked!");
	public int calculatePriceForOrder(Order order){
		int orderPrice = 0;
		for (Item item : order.getItems()){
			orderPrice += getActualPrice(item);
		return orderPrice;

And here is class under test. It  autowires dependencies above.

public class OrderService {
	private PriceService priceService;
	private OrderDao orderDao;
	public int getOrderPrice(int orderId){
		Order order = orderDao.getOrder(orderId);
		return priceService.calculatePriceForOrder(order);

Finally here is test example. It uses field level annotations:

public class OrderServiceTest {
	private static final int TEST_ORDER_ID = 15;
	private static final int TEST_SHOES_PRICE = 2;   
	private static final int TEST_SHIRT_PRICE = 1;
	private OrderService testingObject;
	private PriceService priceService;
	private OrderDao orderDao;
	public void initMocks(){
	public void testGetOrderService(){
		Order order = new Order(Arrays.asList(Item.SHOES, Item.SHIRT));
		//notice different Mockito syntax for spy
		//call testing method
		int actualOrderPrice = testingObject.getOrderPrice(TEST_ORDER_ID);
		Assert.assertEquals(TEST_SHIRT_PRICE + TEST_SHOES_PRICE, actualOrderPrice);

So what happen when you run this test:

  1. First of all TestNG framework picks up @BeforeMethod annotation and invokes initMocks method
  2. This method invokes special Mockito call (MockitoAnnotations.initMocks(this)) to initialize annotated fields. Without this call, these objects would be null. Common mistake with this approach is to forget this invocation.
  3. When all the test fields are populated with desired values, test is called.

This example doesn’t include Spring context creation and Spring’s annotations are here only as examples for usage against production code. Test itself doesn’t include  any dependency to Spring and ignores all its annotations. In fact there could be used EJB annotations instead or it can be running against plain (non IoC managed) private fields.

Developers tend to think about MockitoAnnotations.initMocks(this) call as unnecessary overhead. But it is actually very handy, because it resets testing object and re-initializes mocks. You can use it for example

@Spy annotated object can be created in two ways

Testing object annotated by @InjectMocks can be also initialized explicitly.


Reference: Use Mockito to mock autowired fields from our JCG partner Lubos Krnac at the blog.
Exit mobile version