我正在尝试使用JUnit4测试一个实用程序方法,该方法将javax.ws.rs.core.Response作为输入参数。该方法查看Response属性并根据响应代码执行一些操作。当我在测试方法中创建响应并使用以下命令提交时:
Response resp = Response.status(Status.INTERNAL_SERVER_ERROR).entity(respMessage).build();
ResponseParser.parseResponse(resp);
我的实用程序方法抛出:
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)
我的util类基本上是:
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);
}
}
}
如何按照resteasy的预期创建一个由流正确支持的响应?我查看了很多类似的问题,但它们似乎主要围绕测试或模拟端点调用。我只想测试我的解析方法。
答案 0 :(得分:2)
使用某些单元测试框架(如Mockito)模拟响应。然后,您将能够声明每个响应方法调用返回什么,甚至检查是否已调用方法。
答案 1 :(得分:1)
我最终做了@albert_nil建议的事情。这是我的测试类的相关代码。 MessageParseUtil.parseReportResponse(mockResponse);是正在测试的实用方法。
@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;
}