Spring Boot 集成测试结果在 401

Bex*_*Bex 6 spring-boot

我们有一个暴露 REST api 的 Spring Boot 1.4 Web 应用程序,我们想要运行一些集成测试。

在我们的测试中,我们让 Spring Boot 在本地启动 Web 应用程序,然后我们对 api 进行一些调用。

如果我们简单地运行 Web 应用程序本身并点击端点,我们会得到200/OK响应,这是预期的。然而,运行测试,我们得到了401/Unauthorized服务器响应。

我应该在哪里查看可能导致授权错误的原因?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplication3IT {
    private final Logger log = LoggerFactory.getLogger(DemoApplication3IT.class);

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void getFunky() throws IOException {
        ResponseEntity<String> response =
            this.restTemplate.getForEntity("http://localhost:8080/api/funky", String.class);
        log.info("TestRestTemplate response Code: " + response.getStatusCode());
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); // Expected :200, Actual   :401
    }
}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,使用浏览器访问端点工作正常,但集成测试失败。

Bex*_*Bex 4

最终,问题在于单元测试环境中尚未禁用安全性。解决方案是将以下行添加到application.yml

management.security.enabled: false
management.health.db.enabled: false
security.basic.enabled: false
Run Code Online (Sandbox Code Playgroud)