Springboot:自动解码不适用于TestRestTemplate

时间:2019-04-25 14:38:28

标签: java spring-boot spring-mvc resttemplate urldecode

我有一个运行在Tomcat上的Spring-Boot应用程序。在其中,我有一个带有请求参数的RestController。


@RequestMapping(value = "/v1/test", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
     public String getV2LocationByName(
                                      @RequestParam
                                      String cityName cityName,
                                      @RequestParam(value = LANGUAGE, defaultValue = US_ENGLISH_LOCALE) String language,
                                      HttpServletRequest request) throws InterruptedException, ExecutionException {
--------------
---------------
 System.out.println(cityName);
}

当我调试spring boot应用程序时,请求参数cityName被解码 即,如果URL为http://localhost:8080/v1/test?cityName=Andaman%26Nicobar,它将被解码为http://localhost:8080/v1/test?cityName=Andaman&Nicobar

但是当我写一个春季mvc测试时:

@RunWith(SpringRunner.class)
@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

public class ApplicationTest {


    @LocalServerPort
    private int port;

    TestRestTemplate restTemplate = new TestRestTemplate();

    HttpHeaders headers = new HttpHeaders();

    @Test
    public void testRetrieveStudentCourse() {

            HttpEntity<String> entity = new HttpEntity<String>(null, headers);

            ResponseEntity<String> response = restTemplate.exchange(
                            createURLWithPort("v1/test?cityName=Andaman%26Nicobar"),
                            HttpMethod.GET, entity, String.class);



    }

    private String createURLWithPort(String uri) {
            return "http://localhost:" + port + uri;
    }

当我调试此测试和控制器时,这次没有对cityName进行解码。为什么它会这样?如何为此添加单元测试?

1 个答案:

答案 0 :(得分:0)

解决了这个问题

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WeChatOauthControllerTest {

 @LocalServerPort
    private int port;

    TestRestTemplate restTemplate = new TestRestTemplate();

  @Test
    public void testRetrieveStudentCourse(){
        ResponseEntity<String> response = 
        restTemplate.exchange(createURI("%26"),HttpMethod.GET, null, String.class);
        assertEquals(response.getStatusCode(), HttpStatus.OK);
    }

  private URI createURI(String param){
        URI uri = null;
        String url = "http://localhost:"+ port +"/v1/test?query=" + param;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
           log.error(e.getMessage());
        }
        return uri;
    }