Search code examples
javajakarta-eejunitmockito

How to mock an abstract class with abstract methods using Mockito?


I am currently trying to mock jakarta.ws.rs.core.Response.

@Mock
private Response response;

which is used in my test as

when(response.getStatusInfo()).thenReturn(Response.Status.OK);

However, upon executing I get the following error message: Mockito cannot mock this class: cla...

Upon further research, I came across an article from Baeldung. However, the article does not cover my use case where both the class and the method are abstract. How would I proceed? Do I need to create an implementation of the to-be-tested method?


Solution

  • Add to the dependency

    <dependency>
        <groupId>jakarta.xml.bind</groupId>
        <artifactId>jakarta.xml.bind-api</artifactId>
        <version>4.0.0</version>
    </dependency>
    

    Without it you are right Mokito is not able to mock the method.

    @Test
    public void test() {
        jakarta.ws.rs.core.Response response = mock(jakarta.ws.rs.core.Response.class);
        when(response.getStatusInfo()).thenReturn(jakarta.ws.rs.core.Response.Status.OK);
        assertEquals(jakarta.ws.rs.core.Response.Status.OK, response.getStatusInfo());
    }
    

    Caused by: java.lang.ClassNotFoundException: jakarta.xml.bind.annotation.adapters.XmlAdapter at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) ... 132 more