简体   繁体   中英

Mocking abstract super class method directly from child class

I have a sub class that extends abstract class called AbstractParentClass like

class Child extends AbstractParentClass

This AbstractParentClass contains a method called getParentAbstractServiceMethod which returns some service class object. That services class has another method called getParentAbstractClassDomainFacade which returns some other class object which is not abstract and so on...This is like method chaining.

Snippet inside Child class is as follows

SessionClass userSession = (SessionClass)
getParentAbstractServiceMethod().getParentAbstractClassDomainFacade().getParentAbstractClassDomainObject(SessionClass.NAME);

How to mock getParentAbstractServiceMethod() method since this is abstract class method I cannot instantiate it and call..

The best solution was to follow the "Favour composition over Inheritance" principle and turn the AbstractServiceClass into a regular class that gets the current extenders as dependencies implementing an interface that provides the method to be called on them.


having written this the less advisable solution is to create a mock of the Abstract class using Mockito:

 AbstractParentClass cut= Mockito.mock(AbstractParentClass.class,Mockito.CALLS_REAL_METHODS); Mockito.when(cut.getParentAbstractServiceMethod()).thenAnswer(...);

I think you should step back and look at your design. What is the point of testing a child class (of an abstract class) ... that doesn't implement the abstract methods in the first place.

I think you should do the following:

A) test your base class as far as possible; for example by creating a test only child class that somehow meaningfully implements the abstract methods

B) make sure that your "real" child classes provide reasonable implementations of your abstract methods.

And hint: consider not putting abstract into your method names. They are only abstract on the parent level; not in the childs that implement them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM