Mock a superclass method with Mockito

Say you want to test a method from class which extends some kind of superclass. Sometimes you can be dependent on code in the superclass, which is undesirable in a test.

Now actually, the first thing you should consider is to refactor your code, because it’s violating the Single Responsibility design principle:
there is more than one reason why your class is subject to change. Another advice is to favor composition over inheritence. In this way you can mock the code you are collaborating with.

Having said that, sometimes you run into legacy code you just have to work with and aren’t able to refactor due to circumstances. Here’s a trick I found on Stackoverflow to “mock” a superclass method to do nothing with mockito.

public class BaseController {
public void method() {
validate(); // I don't want to run this!
public class JDrivenController extends BaseController {
public void method(){
load(); // I only want to test this!
public void testSave() {
JDrivenController spy = Mockito.spy(new JDrivenController ());
// Prevent/stub logic in super.method()
// When
// Then


    1. If you would want to mock behaviour that returns something, you could write something like:


      1. what if u want to ignore the mock the response of super.method(), thus ignoring the call to BaseController.method. I assume there’s no need for this -> Mockito.doNothing().when((BaseController)spy).validate(); because I dont want to execute the super.method.. I want to mock it and its return. Any idea?

        1. The productioncode will always be executed, so you will need to deal with it in your test method in someway, hence the explicit code to do nothing.

          If the code does nothing that interferes with the code you want to test, you just write the test for method() like you would normally and don’t deal with the super method.

Leave a Reply

Your email address will not be published. Required fields are marked *