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

后端 未结 3 1605
暖寄归人
暖寄归人 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:17

    As a quick way around, I just added a different proxy method on the subclass that calls super's run. Then you can mock the "proxy".

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-05 01:22

    Here is an example for a class that extends another class and it has some other dependencies. In this case, I'll move the superclass call into the other method and then mock the superclass caller method.

    class Child extends Parent {
    
      @Autowired
      private Dependicy d;
    
      public Authentication authenticate(Authentication auth) {
        the code to be tested...
        superAuthenticate(auth);// the code that I don't want to deal with it.
        return auth;
      }
    
      protected Authentication superAuthenticate(Authentication auth) {
        return super.authenticate(auth);
      }
    }
    

    As you can see above, the authenticate method does some logic and then call the super class's method, so I want to mock the superclass call and test my own code block. Here is my test class:

    @RunWith(MockitoJUnitRunner.class)
    public class ChildTest {
        @Mock
        private Dependicy d;
        @InjectMocks
        private Child child = new Child();
    
        @Test
        public void testSomething() {
            Child spy = Mockito.spy(child);
    
            when(d.aMethod(aParam)).thenReturn(aResult);
            doReturn(usefulResult).when(spy).superAuthenticate(any());
    
            Authentication result = spy.authenticate(auth);
            assertThat(result).isNotNull;
        }
    }
    
    0 讨论(0)
提交回复
热议问题