【问题标题】:Why is TestRestTemplate ignoring a 404 client error?为什么 TestRestTemplate 忽略 404 客户端错误?
【发布时间】:2016-08-03 11:01:18
【问题描述】:

我编写了一个 Spring Boot 控制器,用于侦听发送到 /orders/ 的 PUT 请求。

在我的集成测试中,我注意到TestRestTemplate 没有像我预期的那样对 404 响应做出异常反应。这导致像这样的测试通过:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class OrderControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;


    @Test
    public void testValidPut() throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>("{}", headers);
        restTemplate.put("/doesntexist", entity);
    }
}

当我预计 put 方法会抛出异常时,如 the documentation 中所述:

投掷:
RestClientException - 客户端 HTTP 错误

我已确认,如果我正常运行我的应用程序,我会在尝试 PUT 到同一 URL 时收到 404。

所以要么我没有出于某种原因在这种情况下得到 404,要么我误解了 TestRestTemplate 的工作原理。有什么建议吗?

【问题讨论】:

    标签: java spring http spring-boot integration-testing


    【解决方案1】:

    TestRestTemplate 在设计上具有容错性。这意味着当收到错误响应(400 或更大)时它不会抛出异常。这使得测试错误场景变得更加容易,因为您可以简单地断言响应的状态代码、正文、标头等与相关场景的预期一致,而不必捕获异常。

    【讨论】:

    • 好的,谢谢。听起来像一个小的文档错误。如果我想询问我的 PUT 的结果,我应该切换到调用exchange 而不是put
    • 是的,如果您关心响应,您应该使用交换来获取PUT 请求
    猜你喜欢
    • 2016-02-16
    • 1970-01-01
    • 2013-06-01
    • 2018-08-17
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    相关资源
    最近更新 更多