简体   繁体   English

Mockito的Mocking Jersey客户ClientResponse

[英]Mocking Jersey Client ClientResponse with Mockito

I am having some problems with mocking com.sun.jersey.api.client.ClientResponse but only when I am setting the .type(MediaType.MULTIPART_FORM_DATA_TYPE. 我在模拟com.sun.jersey.api.client.ClientResponse时遇到一些问题,但是仅当我设置.type(MediaType.MULTIPART_FORM_DATA_TYPE时。

I am stuck with jersey-client 1.18. 我被球衣客户端1.18困扰。

Here is the code under test: 这是测试中的代码:

 ClientResponse clientResponse = client.resource(url)
            .accept("application/json")
            .entity(multiPart)
            .type(MediaType.MULTIPART_FORM_DATA_TYPE)
            .post(ClientResponse.class);

Here is the mocking for the test: 这是测试的模拟:

 when(clientResponse.getEntity(String.class)).thenReturn(body);
 when(builder.post(eq(ClientResponse.class))).thenReturn(clientResponse);
 when(builder.type(MediaType.MULTIPART_FORM_DATA_TYPE)).thenReturn(builder);
 when(webResource.accept(anyString())).thenReturn(builder);
 when(client.resource(anyString())).thenReturn(webResource);;

The error I receive is a NullPointerException in the Code under Test at the line: 我收到的错误是受测代码中的NullPointerException行:

 .type(MediaType.MULTIPART_FORM_DATA_TYPE)

Anyone know how to mock the Client.resource().type()? 有人知道如何模拟Client.resource()。type()吗?

If I understand what you're doing, you've mocked a builder. 如果我了解您在做什么,那么您就嘲笑了一个构建器。

You don't have mocking that covers calling builder.entity() on the builder returned by webResource.accept() , so it returns null and the next call in the chain fails ( builder.type() ). 您没有模拟方法涵盖在webResource.accept()返回的builder上调用builder.entity() ,因此它返回null并且链中的下一个调用失败( builder.type() )。

Add: 加:

 when(builder.entity(anyString())).thenReturn(builder);

(provided multiPart is a String ) (提供的multiPartString

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM