gpt4 book ai didi

jersey - 使用 Mockito 模拟 Jersey 客户端

转载 作者:行者123 更新时间:2023-12-02 04:46:50 28 4
gpt4 key购买 nike

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

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

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

谢谢

最佳答案

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

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

关于jersey - 使用 Mockito 模拟 Jersey 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32192095/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com