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

匿名 (未验证) 提交于 2019-12-03 01:38:01

问题:

My Scenario is as 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 of ChildClass and since this method internally calls the super class method, i need some help/piece of code on how to mock the run() method which is present in the childRunner() method of ChildClass.

回答1:

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



回答2:

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;     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!