休息URL的JUnit测试用例

时间:2017-09-21 05:20:06

标签: rest mockito resttemplate

我在为休息网址编写测试用例时遇到问题,该网址通过Rest Template调用另一个URL。

请在下面找到我的代码: -

@RestController
public class ParentController{
@Value("${child.url}")
    private String childUrl;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @RequestMapping(value = "/parent",method = RequestMethod.POST)
    public ResponseEntity<Object> callChildController(@RequestBody InputParam inputParam, HttpServletRequest request) {
        return restTemplateUtil.templateService(restTemplateUtil.formURL(request, childUrl), HttpMethod.POST,null,inputParam, Object.class);
    }}
}


@Service
public class RestTemplateUtil {

    RestTemplate restTemplate = new RestTemplate();

    public  ResponseEntity<Object> templateService(String url, HttpMethod method, HttpHeaders headers, ...............){

            logger.info("Rest template service called..");
            response = restTemplate.exchange(url,method,entity,responseType);

        return response;
    }

    public String formURL(HttpServletRequest request, String childUrl){
        return "http://" + request.getServerName() + ":" + request.getServerPort() + childUrl;
    }
}

JUnit测试案例: -

Mockito.when(restTemplateUtil.templateService(Mockito.anyString(),
                Mockito.<HttpMethod> eq(HttpMethod.POST),
                Mockito.<HttpHeaders> any(),
                Mockito.<HttpEntity<?>> any(),
                Mockito.<Class<Object>> any())).thenReturn(mockRespEntity);

                 this.mvc.perform(post("/parent")
                .contentType(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(requestObj)))
                .andExpect(status().is2xxSuccessful());

我是Mockito的新手,所以凭借我微薄的知识构建了上述测试用例。 如果我错了,请告知并纠正我。

执行此操作时,我收到错误: -

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:80/child": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect

portno在这里是错误的。

请帮忙。

感谢。

0 个答案:

没有答案