I’d like to test an abstract class. Sure, I can manually write a mock that inherits from the class.
Can I do this using a mocking framework (I’m using Mockito) instead of hand-crafting my mock? How?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The following suggestion lets you test abstract classes without creating a "real" subclass – the Mock is the subclass and only a partial mock.
Use
Mockito.mock(My.class, Answers.CALLS_REAL_METHODS), then mock any abstract methods that are invoked.Example:
Note: The beauty of this solution is that you do not have to implement the abstract methods.
CALLS_REAL_METHODScauses all real methods to be run as is, as long as you don’t stub them in your test.In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiable subclass of your abstract class.