Wednesday, May 1, 2013

When there is a class inherited from parent class, how could I mock the parent class with Mockito?

Unit testing consisting of running a series of test case on the particular unit/module, in this case, the unit is referring to a JAVA class. This should not be a problem if it is a standalone class, but things started to get complicated when it comes to inheritance where the parent class is doing all the preliminary work for a child class.

When this is the case, it is impossible for me to execute the test on parent class since the scope of this test is only focus on the child class, which is mine module. It is worth the effort if I could mock the parent class regardless of whether the parent class is running correctly or not and I'll just concentrate on my module.

This is the code snippet I'm trying to do how it could be done.
public class ClassA {

 private int a = 1;
 public int getA() {
  return a;

public class ClassB extends ClassA {

 private int b;
 public int getB() {
  return getA() + b;
 public void setB(int b) {
  this.b = b;

public class TestMainApp {

 ClassA a;
 ClassB b;
 public void setup() {
  a = Mockito.mock(ClassA.class);
 public void testFunctionA() {
  b = new ClassB();
  assertEquals("testFunctionA()", b.getB(), 3);
In this sample, I am trying to mock the parent class, ClassA to return me a value 2 instead of 1, and pass it to ClassB will return me 3. Thus the output of this test is success.

No comments: