How to mock super class method using Mockito or anyother relavent java framework

后端 未结 3 1633
暖寄归人
暖寄归人 2021-01-05 00:54

My Scenario is as below

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

class ChildClass extends S         


        
3条回答
  •  暖寄归人
    2021-01-05 01:21

    Ideally, you should "favor composition over inheritance".

    If you don't have this option you could use doNothing which basically tells Mockito to do nothing when a method in a mock/spy object is called. This was also discussed here

    Following code example should help

    @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");
            run();
            System.out.println("Last Step");
        }
    }
    

    output:

    Step 1
    Last Step
    

    In case you use super.run(); this won't work

提交回复
热议问题