Spring 集成测试,防止重定向能够比较状态码

Spring integration test, prevent redirect to be able to compare status code

我正在尝试对我的 Spring-boot 应用程序进行集成测试。我有一个受保护的端点(/uaa/change_password、Spring MVC),它在未通过身份验证时重定向到 /uaa/login。我如何拦截我发送的请求,我只为 /uaa/login 页面返回 200 OK。因此 assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); 的测试失败,因为状态代码是 200。(另一个测试也失败了)。任何帮助表示赞赏。

代码:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApiAuthServerApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class ApiAuthServerApplicationTests {

    @Value("${local.server.port}")
    private int port;

    private RestTemplate template = new TestRestTemplate();

    @Test
    public void changePasswordPageProtected() {
        ResponseEntity<String> response = template.getForEntity("http://localhost:"
                + port + "/uaa/change_password", String.class);

        assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
        String auth = response.getHeaders().getFirst("WWW-Authenticate");
        assertTrue("Wrong header: " + auth, auth.startsWith("Bearer realm"));
    }
}

我的配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {          
        http
            .formLogin().loginPage("/login").permitAll()
        .and()
            .requestMatchers().antMatchers(                     
                    "/login", 
                    "/oauth/authorize",                     
                    "/oauth/confirm_access", 
                    "/reset_password", 
                    "/forgot_password",
                    "/change_password")     
        .and()
            .authorizeRequests()
            .antMatchers("/reset_password", "/forgot_password").permitAll()             
            .anyRequest().authenticated();
    }

您需要在 RestTemplate 中禁用自动重定向。为此,我推荐 Apache HTTP Client

下面是如何配置 RestTemplate 以不遵循 HTTP 302:

的示例
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

....

HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();
new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));