问题
Hello I am testing Jersey Client 1.19 version using JUnit and Mockito. I am struggling on getting or reading the entity. I don't know how to proceed from there and i am also getting IllegalStateException. Below is the code that i am using to create mock objects for client response.
public class MockJerseyClient {
private ClientConfiguration clientConfig;
private Client client;
private WebTarget webTarget;
private Invocation.Builder invocationBuilder;
private Response response;
private RetrieveBillingResponseXMLReader xmlReader;
private ResponseBuilder responseBuilder;
public MockJerseyClient(String uri, int status, String contentType, String content) {
// Mock Objects
clientConfig = Mockito.mock(ClientConfiguration.class);
client = Mockito.mock(Client.class);
clientConfig.createClient();
webTarget = Mockito.mock(WebTarget.class);
clientConfig.createWebResource(uri);
invocationBuilder = Mockito.mock(Invocation.Builder.class);
xmlReader = new RetrieveBillingResponseXMLReader();
responseBuilder = Response.accepted();
response = responseBuilder.build();
// Rule for Client...
Mockito.when(client.target(uri)).thenReturn(webTarget);
// Rule for ClientConfiguration...
Mockito.when(clientConfig.createWebResource(Mockito.anyString())).thenReturn(webTarget);
// Rules for WebTarget...
Mockito.when(webTarget.path(Mockito.anyString())).thenReturn(webTarget);
Mockito.when(webTarget.register(xmlReader.getClass())).thenReturn(webTarget);
Mockito.when(webTarget.queryParam(Mockito.anyString(), Mockito.anyObject())).thenReturn(webTarget);
Mockito.when(webTarget.request()).thenReturn(invocationBuilder);
// Rules for Invocation.Builder...
Mockito.when(invocationBuilder.header(Mockito.anyString(), Mockito.anyObject())).thenReturn(invocationBuilder);
Mockito.when(invocationBuilder.accept(Mockito.anyString())).thenReturn(invocationBuilder);
Mockito.when(invocationBuilder.get(Response.class)).thenReturn(response);
Mockito.when(response.readEntity(String.class)).thenReturn(content);
// String entity = response.readEntity(String.class);
response.close();
} // end of constructor...
public ClientConfiguration getClientConfiguration() {
return clientConfig;
} // end of method...
If someone could help me how to read the entity based on different content types.
Thanks
回答1:
Tests like this are extremely brittle, as they are too low-level... and in this case you don't assert a lot of things, so you're not testing good enough. It's generally better not to repeat the calls you'll have to make in your client, but instead mock the resource you want to access.
An easy way to do so, is to use a DropwizardClientRule. There's an example in the tests.
来源:https://stackoverflow.com/questions/32192095/mocking-jersey-client-using-mockito