spring-boot – 401中的Spring Boot集成测试结果

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

在我们的测试中,我们获得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
    }
}

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

最佳答案 最终,问题是单元测试环境中没有禁用安全性.解决方案是将以下行添加到application.yml:

management.security.enabled: false
management.health.db.enabled: false
security.basic.enabled: false
点赞