How to mock a superclass method using Mockito or any other Java framework framework

My script is below

class SuperClass{
   public void run(){
      System.out.println("I am running in Super class");
   }
}

class ChildClass extends SuperClass{
  public void childRunner(){
     System.out.println("Step 1");
     System.out.println("Step 2");
     **run();**
     System.out.println("Last Step");
  }
}

Now I want to mock the childRunner()method ChildClass, and since this method internally calls the superclass method, I need help / part of the code on how to mock the method run()that is present in the childRunner()method ChildClass.

+4
source share
1 answer

Similar to what was discussed here: Mockito How to mock a superclass method call

This should work:

@Test
public void tst() {
    ChildClass ch = Mockito.spy(new ChildClass());
    Mockito.doNothing().when((SuperClass)ch).run();
    ch.childRunner();

}

class SuperClass{
    public void run(){
        System.out.println("I am running in Super class");
    }
}

class ChildClass extends SuperClass{
    public void childRunner(){
        System.out.println("Step 1");
        System.out.println("Step 2");
        run();
        System.out.println("Last Step");
    }
}

output:

Step 1
Step 2
Last Step

If you use super.run (); it will not work

+6
source

All Articles