Duncan Duncan - 4 months ago 43
HTTP Question

Why is TestRestTemplate ignoring a 404 client error?

I've written a Spring Boot controller that listens for PUT requests sent to

/orders/
.

In my integration tests, I noticed
TestRestTemplate
is not reacting to a 404 response with an exception as I expected. This leads to a test like this passing:

@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);
}
}


when I would have expected the
put
method to throw an exception, as explained in the documentation:


Throws:

RestClientException - on-client side HTTP error


I've confirmed that if I run my application normally, I get a 404 when attempting to PUT to the same URL.

So either I'm not getting a 404 in this scenario for some reason or I'm misunderstanding how
TestRestTemplate
is working. Any suggestions?

Answer

TestRestTemplate is, by design, fault tolerant. This means that it doesn't throw exceptions when an error response (400 or greater) is received. This makes it easier to test error scenarios as, rather than having to catch an exception, you can simply assert that the response's status code, body, headers, etc are as expected for the scenario in question.