为什么 TestRestTemplate 会忽略 404 客户端错误?

Why is TestRestTemplate ignoring a 404 client error?

我写了一个 Spring 启动控制器,用于侦听发送到 /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:

中所述

Throws:
RestClientException - on-client side HTTP error

我已经确认,如果我 运行 我的应用程序正常,我在尝试 PUT 到相同的 URL.

时会收到 404

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

TestRestTemplate 在设计上是容错的。这意味着它不会在收到错误响应(400 或更大)时抛出异常。这使得测试错误场景变得更容易,因为您不必捕获异常,只需断言响应的状态代码 body、headers 等符合相关场景的预期。