我在创建模拟响应对象以与我的单元测试一起使用时遇到问题。我正在使用org.glassfish.jersey.core.jersey-client
版本2.3.1来实现我的RESTful客户端和mockito
版本1.9.5以帮助我处理模拟对象。这是我的测试代码:无法模拟Glassfish Jersey客户端响应对象
@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。所以我的测试是注定的:(你们/ gals对我在这里可以做什么有所了解吗?我不想用Mockito来模拟Response对象,因为我认为它可能是代码异味,因为它违反了得墨忒耳,真诚的,我的想法在这里。像这样的事情应该是简单明了。
托马斯,感谢您的输入!只有一个问题......如果是你......你会嘲笑readEntity()方法吗? –
这取决于你想测试什么? – Thomas
getAll方法执行它应该执行的操作,并根据它接收的内容返回它应该返回的内容。 –