It’s not a problem to test class for which you can create an instance and execute implemented methods. Little problem starts when you would like to test class without an instance of this class. My way to test abstract classes is to create instance of the class as a mock via Mockito and simulate the behaviour.

In this test I used JUnit 4, Mockito and Hamcrest frameworks. All of them you should add to your Gradle build script:

To test abstract class we should create at least one. Here is an example class:

Definition of the enum used in the implementation:

And simple Warrior implementation of the abstract class:

Tests for the WarriorSkills class are obvious, so I will skip to the CombatSkills unit tests.

The most important part is preparation of the mock with answer attribute: CALLS_REAL_METHODS

@Mock(answer = Answers.CALLS_REAL_METHODS)
private CombatSkills combatSkills;

As an alternative you can use Spy feature from Mockito instead of Mock.

@Spy
private CombatSkills combatSkills;

Now you can execute Gradle wrapper test script to check are all tests pass.

./gradlew test

Output:

:compileJava
:processResources UP-TO-DATE
:classes
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
BUILD SUCCESSFUL
Total time: 6.082 secs

Any insight and other solutions are welcome.

Advertisements