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