我在創建模擬響應對象以與我的單元測試一起使用時遇到問題。我正在使用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方法執行它應該執行的操作,並根據它接收的內容返回它應該返回的內容。 –