问题描述
我们有一个暴露 REST api 的 Spring Boot 1.4 Web 应用程序,我们想要运行一些集成测试.
We've got a Spring Boot 1.4 web app the exposes a REST api, and we want to run some integration tests.
在我们的测试中,我们让 Spring Boot 在本地启动 Web 应用程序,然后我们对 api 进行一些调用.
In our test, we get Spring Boot to spin up the web app locally and then we make some calls against the api.
如果我们简单地运行 Web 应用程序本身并点击端点,我们会得到 200/OK
响应,这是预期的.但是,运行测试时,我们收到了 401/Unauthorized
服务器响应.
If we simply run the web app itself and hit the endpoint, we get 200/OK
response, which is expected. Running the test, however, we are getting a 401/Unauthorized
server response.
在哪里查看可能导致授权错误的原因?
Where would I look to see what might be causing the authorization error?
@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
}
}
奇怪的是,使用浏览器访问端点工作正常,但集成测试失败.
It's strange that hitting the endpoint with a browser works fine, but the integration test fails.
推荐答案
最终,问题是在单元测试环境中没有禁用安全性.解决方案是在 application.yml
中添加以下几行:
Ultimately, the issue was that security had not been disabled in the unit test environment. The solution was adding the following lines to application.yml
:
management.security.enabled: false
management.health.db.enabled: false
security.basic.enabled: false
这篇关于Spring Boot 集成测试结果在 401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!