spring 4.1.1, mockmvc and do not want url encoding of HTTP GET request

匆匆过客 提交于 2019-12-05 04:44:05

What works for me is MockMvcRequestBuilders.get(new URI([ENCODED_URL_STRING])).

I guess there is alternative using MockMvcRequestBuilders.get(String urlTemplate, Object... urlVariables), with appropriate urlVariables, but I haven't gone deeper.

A little late, but I created my own URI matcher to use with MockMvc:

public class RequestToUriMatcher implements RequestMatcher {

    private final String expectedUri;

    public RequestToUriMatcher(String expectedUri){
        this.expectedUri = expectedUri;
    }

    @Override
    public void match(ClientHttpRequest clientHttpRequest) throws IOException, AssertionError {
        URI requestUri = clientHttpRequest.getURI();
        //requestUri is encoded, so if request was made with query parameter already encoded, this would be double-encoded, so decoding it once here
        String decodedUri = URLDecoder.decode(requestUri.toString(), "UTF-8");
        assertTrue(decodedUri.endsWith(expectedUri));
    }
}

Followed by a static method:

public static RequestMatcher requestToUri(String uri){
    return new RequestToUriMatcher(uri);
}

Now I can use it like so:

String uri = "stuff%3Dvalue";
MockRestServiceServer.createServer(restTemplate)
    .expect(requestToUri(uri))/**/

It is not a perfect solution, but for the sake of lack of other solutions, it works...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!