Как заставить TestRestTemplate игнорировать перенаправления - PullRequest
0 голосов
/ 30 октября 2018

Контроллер My Rest возвращает ResponseEntity с HttpStatus.TEMPIRARY_REDIRECT и заголовком Location. В моем интеграционном тесте тело ответа содержит страницу из заголовка перенаправления.

Для целей теста я хотел бы подтвердить статус http и заголовок, но фактически не следовать перенаправлению. Желательно, чтобы я не хотел добавлять новые зависимости в мой проект, если это не имеет смысла.

ОБНОВЛЕНО с примером кода:

RestTestApplication.java

package com.example.resttest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RestTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestTestApplication.class, args);
    }
}

Controller.java

package com.example.resttest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URI;

@RestController
public class Controller {

    @GetMapping("/test1")
    public void test1(HttpServletResponse httpServletResponse) throws Exception {
        httpServletResponse.sendRedirect("www.google.com");
    }

    @GetMapping("/test2")
    public ResponseEntity<String> test2(HttpServletResponse httpServletResponse) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI("http://google.com"));
        return new ResponseEntity<>("Hello", headers, HttpStatus.TEMPORARY_REDIRECT);
    }

    @GetMapping("/test3")
    public ResponseEntity<String> test3(HttpServletResponse httpServletResponse) throws Exception {
        return new ResponseEntity<>("Hello", HttpStatus.TEMPORARY_REDIRECT);
    }
}

RestTestApplication.java

package com.example.resttest;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RestTestApplication.class)
public class RestTestApplicationTests {

    @Autowired
    TestRestTemplate testRestTemplate;

    @LocalServerPort
    int randomServerPort;

    private static RestTemplate staticRestTemplate;

    @BeforeClass
    public static void setUp() throws Exception {
        staticRestTemplate = new RestTemplate();
    }

    /**
     * This doesn't work at all
     */
    @Test
    public void test11_testresttemplate_send_redirect() {
        ResponseEntity<String> response = testRestTemplate.getForEntity("http://localhost:" + randomServerPort + "/test1", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
        // "status":404,"error":"Not Found","message":"No message available","path":"/www.google.com"
    }

    @Test
    public void test12_testresttemplate_send_redirect() {
        ResponseEntity<String> response = testRestTemplate.getForEntity("/test1", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
        // "status":404,"error":"Not Found","message":"No message available","path":"/www.google.com"
    }

    @Test
    public void test13_resttemplate_send_redirect() {
        ResponseEntity<String> response = staticRestTemplate.getForEntity("http://localhost:" + randomServerPort + "/test1", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
        // HttpClientErrorException$NotFound: 404 null
    }

    /**
     * Works, but actually redirects :(
     */
    @Test
    public void test21_testresttemplate_http_entity_location_header() {
        ResponseEntity<String> response = testRestTemplate.getForEntity("http://localhost:" + randomServerPort + "/test2", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
        // HTTP 200 & in body the content of google.com
    }

    @Test
    public void test22_testresttemplate_http_entity_location_header() {
        ResponseEntity<String> response = testRestTemplate.getForEntity("/test2", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
        // HTTP 200 & in body the content of google.com
    }

    @Test
    public void test23_resttemplate_http_entity_location_header() {
        ResponseEntity<String> response = staticRestTemplate.getForEntity("http://localhost:" + randomServerPort + "/test2", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
        // HTTP 200 & in body the content of google.com
    }

    /**
     * Without location header HTTP code is as expected...
     */
    @Test
    public void test31_testresttemplate_http_response_no_header() {
        ResponseEntity<String> response = testRestTemplate.getForEntity("http://localhost:" + randomServerPort + "/test3", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
        // 307,Hello
    }

    @Test
    public void test32_testresttemplate_http_response_no_header() {
        ResponseEntity<String> response = testRestTemplate.getForEntity("/test3", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
        // 307,Hello
    }

    @Test
    public void test33_resttemplate_http_response_no_header() {
        ResponseEntity<String> response = staticRestTemplate.getForEntity("http://localhost:" + randomServerPort + "/test3", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
        // 307,Hello
    }

}

1 Ответ

0 голосов
/ 31 октября 2018

Чтобы ответить на мой вопрос:

Добавление HTTP-клиента Apache в качестве тестовой зависимости помогло.

...