Search code examples
javamockitopowermockito

How to mock inherited protected method from abstract class


Given a abstract class

public abstract class ClassA
{

   protected String getName()
   {
    return "my name"
   }

}

public class ClassB extends ClassA{
   public String doSomething(){
     String name = getName();
     return name + " cool ";
   }
}

public class TestClass { 

     @Before 
     public void setUp() { 
       MockitoAnnotations.initMocks(this); 
     } 

     @Test public void testDoSomething() { 
          ClassB b = new ClassB();
          b.doSomething();
     } 
} 

How to mock getName() and return a specific value while writing test for doSomething method for classB.


Solution

  • @Test
    public void testcase() {
        ClassB classB= spy(ClassB.class);
        when(classB.getName()).thenReturn(""); 
        classB.doSomething();
    
    }