【发布时间】:2017-10-21 17:22:04
【问题描述】:
我正在尝试使用 PowerMockito 模拟 http 调用,但我在使用 contains() 函数时遇到了一些问题。
我的计划是检查路径是否包含某个字符串,然后返回模拟对象。
所以我有以下功能:
import static com.mscharhag.oleaster.runner.StaticRunnerSupport.*;
import static org.mockito.Matchers.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.powermock.api.mockito.PowerMockito.*;
private static <T> void mockResponse(Class<T> type, T response, String pathContains) throws Exception
{
mockStatic(ClientBuilder.class);
Client client = mock(Client.class);
when(ClientBuilder.class, "newClient").thenReturn(client);
WebTarget webTarget = mock(WebTarget.class);
when(client.target(anyString())).thenReturn(webTarget);
//This is what doesn't work
when(webTarget.path(contains(pathContains))).thenReturn(webTarget);
when(webTarget.queryParam(any(), any())).thenReturn(webTarget);
Invocation.Builder invocationBuilder = mock(Invocation.Builder.class);
when(webTarget.request()).thenReturn(invocationBuilder);
Invocation invocation = mock(Invocation.class);
when(invocationBuilder.buildGet()).thenReturn(invocation);
Response res = mock(Response.class);
when(invocation.invoke()).thenReturn(res);
when(res.readEntity(type)).thenReturn(response);
}
mockResponse(GenreList.class, new GenreList(new Genre(0, "g")), "genre");
问题是我在尝试进行 HTTP 调用时得到一个空指针:
Response res = client.target(theMovieDbURL)
.path("/3/genre/movie/list")
.queryParam("api_key", apiKey)
.request()
.buildGet()
.invoke();
如果我在哪里将模拟从contains() 更改为anyString(),它就像一个魅力,但我需要对不同的路径有不同的响应,所以我不能将它保留为anyString()。我也尝试将其更改为eq(),但它也不起作用。
我在这里缺少什么?
来自我的毕业生:
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.6.6'
testCompile group: 'org.powermock', name: 'powermock-api-mockito', version: '1.6.6'
testCompile group: 'org.powermock', name: 'powermock-module-junit4-rule', version: '1.6.6'
【问题讨论】:
-
请提供您测试的模拟准备部分。您共享的代码中没有调用
mockResponse。 -
@AlehMaksimovich 现在就在那里 :)
-
我现在唯一的想法是您可能使用了错误的
contains。您可以添加静态导入部分吗? -
有趣的是我无法重现您的问题。
when(webTarget1.path(contains("genre"))).thenReturn(webTarget1);以及doReturn(webTarget2).when(webTarget2).path(contains("genre"));和when(webTarget3.path(matches(".*genre.*"))).thenReturn(webTarget3);对我来说一切都有效。最后一个问题,您使用的是哪个版本的 PowerMock 和 Mockito? -
这真的很奇怪......我已经从我的 gradle 文件中附加了部分。你用的是什么版本?
标签: java testing mocking powermock