Spring Bootのコントローラー内でRestTemplateを使った外部HTTPアクセスを実装しています。
JUnitで正常系のテストを実行したのですが、RestClientExceptionが発生し、メソッドの最後まで到達ができません。
デバックしてみると、下記のようなエラーメッセージがでてきたのですが、解決方法がよくわかりません。
どのように対処すればよいのでしょうか。
I/O error on POST request for "外部URL": Connection refused: connect
SampleControllerTest
1@RunWith(SpringRunner.class) 2@SpringBootTest 3public class SampleControllerTest { 4 private MockMvc mockMvc; 5 6 @InjectMocks 7 private SampleController controller; 8 9 @Before 10 public void setUp() throws Exception { 11 MockitoAnnotations.initMocks(this); 12 mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); 13 } 14 15 @Test 16 public void sample() throws Exception { 17 Map<String, String> map = new LinkedHashMap<String, String>(); 18 19 MockRestServiceServer mockServer = MockRestServiceServer.createServer(new RestTemplate()); 20 mockServer 21 .expect(requestTo("外部URL")) 22 .andExpect(method(HttpMethod.POST)) 23 .andRespond(withSuccess(map.toString(), MediaType.APPLICATION_JSON_UTF8)); 24 25 mockMvc.perform(post("/")) 26 .andExpect(status().isOk()) 27 .andExpect(view().name("index")); 28 } 29 30} 31
SampleController
1@Controller 2public class SampleController { 3 @RequestMapping(value = "/", method = RequestMethod.POST) 4 public ModelAndView index() { 5 ModelAndView modelAndView = new ModelAndView(); 6 7 MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>(); 8 formParams.add("data", "data"); 9 10 HttpHeaders httpHeaders = new HttpHeaders(); 11 httpHeaders.add(HttpHeaders.AUTHORIZATION, "Basic XXXXXXXXXX"); 12 httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); 13 RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(formParams, httpHeaders, 14 HttpMethod.POST, URI.create("外部URL")); 15 16 RestTemplate restTemplate = new RestTemplate(); 17 18 ResponseEntity<Map<String, String>> responseEntity = null; 19 try { 20 responseEntity = restTemplate.exchange(requestEntity, new ParameterizedTypeReference<Map<String, String>>() {}); 21 } catch (RestClientException e) { 22 modelAndView.setViewName("error"); 23 return modelAndView; 24 } 25 26 modelAndView.setViewName("index"); 27 return modelAndView; 28 } 29}
回答1件
あなたの回答
tips
プレビュー