How to test abstract class

Testing an abstract class in JUnit is totally doableβ€”you just need a concrete subclass (real or mock) that lets you exercise the logic of the abstract class.

Here are 3 main ways to test an abstract class with JUnit:


βœ… 1. Create a Simple Concrete Subclass for Testing

This is the cleanest approach.

πŸ§ͺ Example Abstract Class

public abstract class Animal {
    public String speak() {
        return getSound();
    }

    protected abstract String getSound();
}

πŸ§ͺ Create a Test Subclass Inside Your Test

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class AnimalTest {

    // Local test subclass
    static class Dog extends Animal {
        @Override
        protected String getSound() {
            return "Woof";
        }
    }

    @Test
    void testSpeak() {
        Animal dog = new Dog();
        assertEquals("Woof", dog.speak());
    }
}

βœ… 2. Use an Anonymous Inner Class

Quick and clean for one-off test cases.

@Test
void testSpeakWithAnonymousClass() {
    Animal testAnimal = new Animal() {
        @Override
        protected String getSound() {
            return "Meow";
        }
    };

    assertEquals("Meow", testAnimal.speak());
}

βœ… 3. Use Mockito to Mock the Abstract Class

Mockito can mock abstract classes and even override specific methods.

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

public class AnimalMockitoTest {

    @Test
    void testSpeakWithMockito() {
        Animal mockAnimal = mock(Animal.class);
        when(mockAnimal.getSound()).thenReturn("Roar");

        // When calling speak(), it internally calls getSound(), which is mocked
        when(mockAnimal.speak()).thenCallRealMethod();

        assertEquals("Roar", mockAnimal.speak());
    }
}

πŸ“ Note: Make sure you're using Mockito 2+ or higher.


πŸ“Œ Summary

MethodWhen to Use
Concrete subclassβœ… Best for reusable tests
Anonymous inner classβœ… Quick tests with minimal setup
Mockito mockβœ… Great when mocking partial behavior