Reputation: 1030
I am trying to use JUnit4 test a utility method that takes a javax.ws.rs.core.Response as an input parameter. The method looks at the Response attributes and takes some action based on the response code. When I just create a response in my test method and submit it using:
Response resp = Response.status(Status.INTERNAL_SERVER_ERROR).entity(respMessage).build();
ResponseParser.parseResponse(resp);
My utility method throws:
java.lang.IllegalStateException: RESTEASY003290: Entity is not backed by an input stream
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:231)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:218)
My util class is basically:
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
public class ResponseParser {
public static void parseResponse(Response response) {
String errorResp = "";
if (!response.getStatusInfo().getFamily().equals(Family.SUCCESSFUL)) {
int errorCode = response.getStatus();
errorResp = response.readEntity(String.class);
}
}
}
How can I create a response that will be properly backed by a stream as expected by resteasy? I looked at quite a few similar questions but they mostly seemed to be centered around testing or mocking an endpoint call. I just want to test my parsing method.
Upvotes: 4
Views: 7632
Reputation: 1030
I did end up doing what @albert_nil suggested. Here is the relevant code from my test class. MessageParseUtil.parseReportResponse(mockResponse); is the utility method that is being tested.
@Test
public void parse_Report_Response_400_Test() {
String respMessage = "400 : Validation error occurred. Invalid Parm: employeeID";
Response mockResponse = buildMockResponse(Status.INTERNAL_SERVER_ERROR, respMessage);
try {
MessageParseUtil.parseReportResponse(mockResponse);
fail("Expected parseReportResponse() to throw error but none thrown.");
} catch (RestClientException e) {
Assert.assertEquals("Expected to status code to be 400 but was " + e.getStatusCode() + " instead.", 400, e.getStatusCode());
Assert.assertEquals("The error message was missing or not correct.", respMessage, e.getErrorMessage().getErrorMessageList().get(0));
}
}
private Response buildMockResponse(Status status, String msgEntity) {
Response mockResponse = mock(Response.class);
Mockito.when(mockResponse.readEntity(String.class)).thenReturn(msgEntity);
Mockito.when(mockResponse.getStatus()).thenReturn(status.getStatusCode());
Mockito.when(mockResponse.getStatusInfo()).thenReturn(status);
return mockResponse;
}
Upvotes: 3
Reputation: 1658
Mock the Response with some unit testing framework, like Mockito. Then you will be able to declare what to return on each response method call, or even check if a method has been called.
Upvotes: 2