Home > Blockchain >  How to mock protected variable in super class using Mockito
How to mock protected variable in super class using Mockito

Time:10-04

I have a parent class ClassA.

public class ClassA{
  protected EntityClass entity;
}

This is my child class ClassB.

public class ClassB extends ClassA {
   public String someMethod(String input) {
      return entity.execute(input);
   }
}

EntityClass is -

public class EntityClass {
  public String execute(String input) {
     return "execute";
  }
}

In Test class I want to test someMethod(input) method in ClassB. For that I would like to mock method call entity.execute(input).

I am completely beginner in TestNG and Mockito. Can anyone help me with how to do that?

CodePudding user response:

Simplest solution, define one more child class on test level, i.e. inside the test case it self, and inject mock or spy in constructor. Then you can perform your testing, for example:

public static class EntityClass {
    public String execute(String input) {
        return "execute";
    }
}

public static class ClassA {
    protected EntityClass entity;
    public ClassA(EntityClass entity) {
        this.entity = entity;
    }
    public ClassA() {
        this( new EntityClass() );
    }
}

public static class ClassB extends ClassA {
    
    public String someMethod(String input) {
        return entity.execute(input);
    }
}

public static class ClassBSpyed extends ClassB {
    private ClassBSpyed() {
        this.entity = Mockito.mock(EntityClass.class);
        Mockito.doReturn("SpyedResult").when(this.entity).execute(Mockito.anyString());
    }
}

@Test
public void shoulCallMocked() throws Exception {
    ClassBSpyed spy = new ClassBSpyed();
    assertEquals("SpyedResult",  spy.someMethod("LoremIpsum"));
}
  • Related