Mocking Abstract classes

In this post under Mockito, I will show with example how to create mock of an abstract class

For our example we will use below abstract class

Shape

package package4;
public abstract class Shape {
public abstract int calculateArea();
public void display() {
System.out.println("Area is:" + calculateArea());
}
}

Below is the test class where we create a mock of “Shape” class

Test class

package package4;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(MockitoExtension.class)
public class ShapeTest {
@Mock
private Shape shape;
@Test
public void testMethod1() {
assertNotNull(shape);
}
}

In the above code, at line 13, I declare a field named “shape” of type “Shape” class. We annotate it with “@Mock” annotation.

So creating a mock of an abstract class is similar to creating a mock of non-abstract class.

Leave a comment