PumpingSalad
PumpingSalad

Reputation: 157

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?

Upvotes: 1

Views: 1213

Answers (2)

Pp88
Pp88

Reputation: 1082

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

Upvotes: 1

Ashish Patil
Ashish Patil

Reputation: 4604

You can use answer parameter of Mock annotation & call your test method somewhat similar to below.

I am using AbstractList & its get method to demonstrate calling abstract method of abstract class .

@Mock(answer = Answers.CALLS_REAL_METHODS)
AbstractList<String> ls;

@Test
void testing() {
   when(ls.get(0)).thenReturn("AA");
   System.out.println(ls.get(0)); // prints "AA"    
}

Hope this helps.

Upvotes: 1

Related Questions