简体   繁体   中英

How to encode JSON as request parameter using Spring MockMVC

I've been trying for a couple of hours to encode JSON as a request parameter for a test I'm writing using Spring's MockMVC but with no luck.

My test looks like

@Before
public void setUp() {       
    mockMvc = MockMvcBuilders.standaloneSetup(new TestController())
            .build();
}

@Test
public void shouldReturnJSONGeneratedByView() throws Exception {
    String sampleJson = "{\"key\":\"value\"}";

    String json = UriComponentsBuilder.newInstance()
    .path(sampleJson)
    .build().encode().toUriString();

    mockMvc.perform(MockMvcRequestBuilders.get("/Node?json="+json))
    .andExpect(status().isOk());
}

But the String that reaches my controller is still encoded ("%7B%22key%22:%22value%22%7D") and so can't be deserialized as JSON.

What am I missing to get Spring to understand encoded parameters?

Thanks for any help

I believe your JSON is being encoded twice, and therefore the controller receives a String that is still encoded (after having been decoded only once).

The JavaDoc for MockMvcRequestBuilders states the following about the first parameter to get :

urlTemplate - a URL template; the resulting URL will be encoded

Therefore I think you don't need to encode the JSON yourself, and the following should work:

mockMvc.perform(MockMvcRequestBuilders.get("/Node?json={json}", sampleJson))
.andExpect(status().isOk());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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