Skip to content

How to return a mock response object from HTTP request?

I’m new to Java programming and I have the following snippet on which I want to write unit test:

Response response = request.get();
if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
     return response.readEntity(type);

I’m able to create the scenario where HTTP request returns a valid response using the below code:


I want to create another scenario where the method call response.readEntity(type) throws an exception. For this, I require that request.get() method returns me a mocked object so that I can define the desired behavior on the mocked object. I read the documentation provided at to find how to do this behavior but didn’t find any way to return a mocked object as HTTP response.

Also, the request variable is not injected and hence I can’t mock it directly.


You cannot do something like

stubFor(get("/$metadata?annotations=true").willReturn(aResponse().withStatus(200).withBody(Mock()));. It is because wiremock acts only as http server mock. Only thing you can configure is response (ex. in JSON). What you can do is to return for example 400 and error code body from wiremock and check if you code accepts this message and act on it correctly.