I have an abstract class which contains logic in concrete methods:
public abstract class AbstractEventHandler implements EventHandler {
private final Dependency dependency;
public AbstractEventHandler(Dependency dependency) {
this.dependency = dependency;
}
@Override
void handleEvent(Event event) {
dependency.doSomeWork();
[...]
doHandleEvent(event);
[...]
}
@Override
void handleOtherEvent(OtherEvent otherEvent) {
dependency.doOtherWork();
[...]
doHandleOtherEvent(event);
[...]
}
protected abstract doHandleEvent(event);
protected abstract doHandleOtherEvent(event);
}
Explored solutions to test my abstract class:
- create a dummy implementation of the abstract class (good point for constructors Mocking an abstract class and injecting classes with Mockito annotations?)
- test the
handleEvent(event)
logic in concrete classes but I would have to duplicate the test in every concrete classes (or once, but in which class?) - use
PowerMock
... - use
Mockito
to instantiate an implementation of the abstract class and call real methods to test logic in concrete methods
I chose the Mockito
solution since it's quick and short (especially if the abstract class contains a lot of abstract methods).
@ExtendWith(MockitoExtension.class)
class AbstractEventHandlerTests {
@Mock
private Dependency dependency;
@InjectMocks
@Mock(answer = Answers.CALLS_REAL_METHODS)
private AbstractEventHandler abstractEventHandler;
Since @InjectMocks
is not permitted on a field already annotated with @Mock
, how can I inject mocked dependencies in my abstract class?