Springboot: автоматическое декодирование не работает с TestRestTemplate - PullRequest
0 голосов
/ 25 апреля 2019

У меня есть приложение Spring-Boot, работающее на Tomcat. В нем есть 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);
}

Когда я отлаживаю приложение весенней загрузки, параметр 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 голосов
/ 29 апреля 2019

Решил проблему с этим

@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;
    }
...