samedi 21 octobre 2017

powermock contains() not working

I am trying to mock an http call using PowerMockito, but I am having some problems with the contains() function. My plan is to check if the path contains a certain string and then I return the mock object. So I have the following function:

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);
}

Problem is that I get a nullpointer when I am trying to make an HTTP call:

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

If I where to change the mock from contains() to anyString() it works like a charm, but I need to have different responses for different paths, so I can't leave it as anyString(). I've tried changing it to eq() as well, but it doesn't work either.

What is it that I am missing here?

Aucun commentaire:

Enregistrer un commentaire