使用Mockito模拟泽西客户端

时间:2015-08-24 21:33:38

标签: jersey

您好我正在使用JUnit和Mockito测试Jersey Client 1.19版本。我正在努力获取或阅读实体。我不知道如何从那里继续,我也得到IllegalStateException。 下面是我用来为客户端响应创建模拟对象的代码。

公共类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...

如果有人可以帮助我如何根据不同的内容类型阅读实体。

由于

1 个答案:

答案 0 :(得分:0)

这样的测试非常脆弱,因为它们太低级......在这种情况下,你不会断言很多东西,所以你的测试不够好。通常最好不要重复您在客户端中必须进行的调用,而是模拟您要访问的资源。

一种简单的方法是使用DropwizardClientRulethe tests中有一个示例。