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.


This entry was posted in Coding, TDD by Arthur. Bookmark the permalink.

About Arthur

My name is Arthur Arts and I love creating great software and making customers happy by delivering value. I'm an avid student of all things concerning Agile Development and Lean Thinking. I love the pragmatism and common sense that lies beneath it.

5 thoughts on “Mock a superclass method with Mockito

  1. Too bad it does not actually allow you to stub the call to the parent method. If the parent contains a lot of logic, you have to prevent/stub all that logic. Yay legacy code :(

  2. I’m trying to use this with my code – but I am getting an error that says Mockito cannot mock this class: MicroServiceClient can only mock visible & non-final classes. ”

    My object extends another object, and uses an interface. Could it be the interface that’s causing the problem? I can’t see what else would be different from your example.

Leave a Reply

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