Using Mockito to mock some methods but not others


In this post I am going to show you how to create partial mocks using Mockito.
Partial mocks are useful when you only need to mock some methods of an object leaving the remainder free to respond to calls normally (i.e. as implemented).

I often reach out for partial mocks when I am writing tests for a method which in turn invoke other methods in the same class and these methods are difficult to set up because they use a bunch of class variables.

Look at the class below.

class OrderItem {
    private Product product;
    private Integer quantity;
    private Money unitPrice;

    public Money price() {
        Money price = unitPrice.multiple(quantity);
    public void auditOperation() {
        // Logic involves setting up a lot of state. i.e class variables

Assume I want to test the price() method and am not too concerned with the auditOperation() logic. I would like to test the implementation for the price() method while mocking out the implementation for the auditOperation() method. This is when I reach out for partial mocks because they let me mock out the auditOpertion() method while still letting me test the price() method.

Warning: partial mocks should be used with caution. They are pointing at a smell in your design.

With Mockito you can achieve partial mocks using either mock() or spy()

With mock() methods are mocked by default and real implementation is used only if it is explicitly coded to do so.

List mockList = mock(LinkedList.class);

//by default, calling the methods of mock object will do nothing

//mock object will call the real method

Conversely with the spy() real implementation is invoked by default and mocked responses need to be explicitly coded.

List spyList = spy(list);

//spy object will call the real method

//spy object will return mocked response

This rounds up our discussion on how to create partial mocks using Mockito.
If you found this useful don’t forget to share it 🙂