powermock contains()不起作用

时间:2017-10-21 17:22:04

标签: java testing mocking powermock

我正在尝试使用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调用时,我得到一个nullpointer:

    Response res = client.target(theMovieDbURL)
                         .path("/3/genre/movie/list")
                         .queryParam("api_key", apiKey)
                         .request()
                         .buildGet()
                         .invoke();

如果我将模拟从contains()更改为anyString(),它就像魅力一样,但我需要对不同的路径有不同的响应,所以我不能将其保留为{ {1}}。我也尝试将其更改为anyString(),但它也无效。

我在这里失踪的是什么?

来自我的gradle:

eq()

1 个答案:

答案 0 :(得分:0)

更多的不答案:你在这里错误的兔子洞。

事情是:测试的目的是确保特定生产代码实现测试应涵盖的要求。没有其他的。

导致:您更喜欢对能够处理许多不同方面的单个代码进行多个简单,直接的测试。

含义:你不去开始使用

when(webTarget.path(contains(pathContains))).thenReturn(webTarget);

你可以看到包含()的各种不同的可能性。相反,你宁愿有n个明确说出

的测试
when(webTarget.path(contains(A))).thenReturn(webTargetA);

...

when(webTarget.path(contains(B))).thenReturn(webTargetB);

换句话说:您打算以某种方式在测试代码中表达聪明的“业务逻辑”。你想让它变得“聪明”。不要那样做。而是专注于编写测试代码,如上所述,直接创建特定设置,然后测试一个事物。

换句话说:测试代码中应该 no 需要提供参数特定的返回值。因为定义了生产代码将看到的设置(以及路径)。你告诉它在一次测试中采用路径A,在另一次测试中采用路径B.然后你想要精心制作if / then逻辑在空气中消失。