【发布时间】:2013-11-02 16:08:55
【问题描述】:
我在创建用于单元测试的模拟 Response 对象时遇到问题。我正在使用org.glassfish.jersey.core.jersey-client 2.3.1 版来实现我的RESTful 客户端和mockito 1.9.5 版来帮助我处理模拟对象。这是我的测试代码:
@Test
public void testGetAll() throws IOException {
// Given
String expectedResource = "expectedResource"
final Response expectedRes = Response.ok(expectedResource, MediaType.APPLICATION_JSON).build();
String receivedResource;
BDDMockito.given(this.client.getSimpleClient().getAllWithResponse()).willReturn(expectedRes);
// When
receivedResource = this.client.getAll();
// Then
Assert.assertNotNull("Request constructed correctly and response received.", receivedResource);
Assert.assertEquals("Resource is equal to expected.", expectedResource, receivedResource);
}
在执行this.client.getAll(); 时会出现问题。这是该方法的代码:
public String getAll() throws GenericAragornException, ProcessingException{
Response response = this.simpleClient.getAllWithResponse();
if (response.getStatus() != 200) {
processErrorResponse(response);
}
String entity = response.readEntity(String.class);
// No errors so return entity converted to resourceType.
return entity;
}
请注意,我正在使用手动创建的响应来模拟 this.simpleClient.getAllWithResponse() 方法。当它到达response.readEntity(resourceListType); 指令时,Jersey 会抛出以下异常:java.lang.IllegalStateException - Method not supported on an outbound message.。经过大量的研究和调试,事实证明,由于某种原因,当我使用响应构建器(例如Response.ok(expectedResource, MediaType.APPLICATION_JSON).build();)创建响应时,它会将其创建为 OutboundResponse 而不是 InboundResponse。后者是唯一允许使用Response.readEntity() 方法的方法。如果是OutboundResponse,则抛出异常。
但是,我找不到将手动创建的响应转换为 InboundResponse 的任何方法。所以我的测试注定要失败:(。你们知道我能在这里做什么吗?我不想用 Mockito 模拟 Response 对象,因为我认为它可能是代码味道,因为它违反了法律得墨忒耳。真的,我在这里没有想法。这样的事情应该简单明了。
【问题讨论】:
标签: unit-testing glassfish mockito jersey-client jersey-2.0