How can I test a method which invoke protected (unwanted) methods of parent class?

早过忘川 提交于 2019-12-03 16:38:15

Did you consider variant to change design of your classes and use composition instead of inheritance ? Then you will be able to just mock / spy instance of class A and inject it to instance of class B. In such case you will be able to configure whatever behavior that you need.

I really not sure doCallRealMethod() will make trick for you, cause you have option to mock method or invoke real one, but not both simultaneously.

If I understood you correctly, you want to test the method 'mainMethod' from class B. So, you should mock an object from class B, and not one from class A. Try this:

/* Given */
B b = Mockito.mock(B.class);

//use this to skip the method execution
Mockito.doNothing().when(b).generifiedMethod(Mockito.anyString(), Mockito.any());
Mockito.doNothing().when(b).method(Mockito.anyInt());

//or use this to return whatever you want when the methods are called
Mockito.doReturn(new Object()).when(b).method(Mockito.anyInt());
Mockito.doReturn(new Object()).when(b).generifiedMethod(Mockito.anyString(), Mockito.any());

Then you can call the mainMethod from B, already knowing what the other methods will return.

I think you are in a case where you should not use a mock library, but revert to the old specialized stub mode.

You have to create a specialized A that has the following functionnalities :

  • note that methods method, generifiedMethod and mainMethod have been called
  • reset the above indicators
  • give read access to the above indicators.

You can then construct your tests with Junit or TestNG. The main problem that remain IMHO is that you probably will have to use a custom build procedure to load the A stub class and not the real A.

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