1+ package org .baeldung .web .handler ;
2+
3+ import org .baeldung .web .exception .NotFoundException ;
4+ import org .baeldung .web .model .Bar ;
5+ import org .junit .Assert ;
6+ import org .junit .Test ;
7+ import org .junit .runner .RunWith ;
8+ import org .springframework .beans .factory .annotation .Autowired ;
9+ import org .springframework .boot .test .autoconfigure .web .client .RestClientTest ;
10+ import org .springframework .boot .web .client .RestTemplateBuilder ;
11+ import org .springframework .http .HttpMethod ;
12+ import org .springframework .http .HttpStatus ;
13+ import org .springframework .test .context .ContextConfiguration ;
14+ import org .springframework .test .context .junit4 .SpringRunner ;
15+ import org .springframework .test .web .client .ExpectedCount ;
16+ import org .springframework .test .web .client .MockRestServiceServer ;
17+ import org .springframework .web .client .RestTemplate ;
18+
19+ import static org .springframework .test .web .client .match .MockRestRequestMatchers .method ;
20+ import static org .springframework .test .web .client .match .MockRestRequestMatchers .requestTo ;
21+ import static org .springframework .test .web .client .response .MockRestResponseCreators .withStatus ;
22+
23+ @ RunWith (SpringRunner .class )
24+ @ ContextConfiguration (classes = { NotFoundException .class , Bar .class })
25+ @ RestClientTest
26+ public class RestTemplateResponseErrorHandlerIntegrationTest {
27+
28+ @ Autowired private MockRestServiceServer server ;
29+ @ Autowired private RestTemplateBuilder builder ;
30+
31+ @ Test (expected = NotFoundException .class )
32+ public void givenRemoteApiCall_when404Error_thenThrowNotFound () {
33+ Assert .assertNotNull (this .builder );
34+ Assert .assertNotNull (this .server );
35+
36+ RestTemplate restTemplate = this .builder
37+ .errorHandler (new RestTemplateResponseErrorHandler ())
38+ .build ();
39+
40+ this .server
41+ .expect (ExpectedCount .once (), requestTo ("/bars/4242" ))
42+ .andExpect (method (HttpMethod .GET ))
43+ .andRespond (withStatus (HttpStatus .NOT_FOUND ));
44+
45+ Bar response = restTemplate .getForObject ("/bars/4242" , Bar .class );
46+ this .server .verify ();
47+ }
48+ }
0 commit comments