Using Mockito’s Spy to mock hierarchical objects
Mocking in Mockito using mock() method is straight-forward for POJO(s) with no inheritance. However for objects which are defined as part of class hierarchies, using mock() to alter parental behaviour cannot be implemented. Lets take an example of a base class such as Staff with derived classes: Employee and Contractor as given below:
public class Staff {
protected String name;
protected Integer age;
protected String deptname;
//other fields, setters and accessors.
}
The Employee/Contractor class look like this
public class Employee extends Staff {
private String employeeID;
private Date joinDate;
//setters and accessors.
}
public class Contractor extends Staff {
private String contractorID;
private String fromCompany;
private Long contractDuration'
//setters and accessors.
}
Lets now mock Contractor object and stub the name (parental attribute) behaviour:
Contractor contractor = mock(Contractor.class);
when(contractor.getName()).thenReturn("John Smith");
assertEquals(contractor.getName(), "John Smith");
Unfortunately the above code is not able to induce name behaviour using stubbing and assertEquals fails in the above code . Now Mockito provides spy() for creating pseudo mock on real objects. This indeed provides a breather to mock hierarchical objects as show below for the example we have
Contractor contractor = new Contractor();
contractor.setName("John Smith");
Contractor mocked = spy(contractor);
//other stubbing logic
assertEquals(contractor.getName(), "John Smith");
This way we can alter functional behaviour for parental properties as well.