【问题标题】:mock a request entity call for unit test模拟单元测试的请求实体调用
【发布时间】:2019-03-25 06:13:25
【问题描述】:

我想模拟请求实体和响应以测试控制器方法上的方法,此代码已由另一个开发人员编写,我应该使用 mockito 对其进行测试。我正在模拟控制器类

我正在尝试模拟请求实体值和响应实体值,但它不起作用,并且在我尝试调试时遇到反射错误

    public class InquiryController {

private static final Logger log = 
    LoggerFactory.getLogger(InquiryController.class);

@Autowired
private InquiryProperties inquiryProperties;

@Autowired
private InquiryService inquiryService;


@Autowired
RestTemplate restTemplate;

public static int count = 0;


@Bean
private RestTemplate getRestTemplate() {
    return new RestTemplate();
}

    @PostMapping(value = "/endCustomer", produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {
        MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<List<EndCustomerDTO>> endCustomer(@RequestBody CustomerInfo customerInfo)
        throws IOException, JSONException {

    log.info("### InquiryController.endCustomer() ===>");
    List<EndCustomerDTO> endCustomerDTOs = null;

    try {

        //RestTemplate restTemplate = new RestTemplate();
        RequestEntity<CustomerInfo> body = RequestEntity.post(new URI(inquiryProperties.getEndCustomer()))
                .accept(MediaType.APPLICATION_JSON).body(customerInfo);
        ResponseEntity<List<EndCustomerDTO>> response = restTemplate.exchange(body,
                new ParameterizedTypeReference<List<EndCustomerDTO>>() {
                });
        endCustomerDTOs = (response != null ? response.getBody() : new ArrayList<EndCustomerDTO>());

    } catch (RestClientException | URISyntaxException e) {
        log.error("InquiryController.endCustomer()" + e.getMessage());
    }

    log.info("### END InquiryController.endCustomer()  ===>");

    if (null == endCustomerDTOs) {
        return new ResponseEntity<List<EndCustomerDTO>>(new ArrayList<EndCustomerDTO>(), HttpStatus.OK);
    }
    return new ResponseEntity<List<EndCustomerDTO>>(endCustomerDTOs, HttpStatus.OK);

}

【问题讨论】:

  • 看起来您正在...尝试混合配置和控制器?用构造函数注入替换字段注入并使用RestOperations 接口而不是RestTemplate,您将能够轻松地模拟依赖关系。

标签: java rest junit mockito resttemplate


【解决方案1】:

这是因为当您进行 REST 调用时,RestTemplate 的实例没有通过 Spring IOC 注入。您需要在应用程序启动期间或换句话说在组件扫描期间扫描的组件类中声明getRestTemplate 方法。从而使restTemplate 可用于autowire

【讨论】:

    【解决方案2】:

    按照@chrylis 的建议将配置与控制器分开后,您可以像这样继续进行。

    您一定是在尝试模拟 RequestEntity.post 方法。请注意,它是一个静态方法,其模拟方式与通常的公共实例方法略有不同。为此,您需要使用 PowerMockito,因为 Mockito 不会。

    像这样在 pom 中添加依赖:

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.6.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.6.5</version>
        <scope>test</scope>
    </dependency>
    

    然后用@RunWith@PrepareForTest 注释测试类,如下所示:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({RequestEntity.class})
    public class TestClass {
    }
    

    然后模拟 post 方法:

    PowerMockito.mockStatic(RequestEntity.class);  when(RequestEntity.post(any(URI.class))).thenReturn(getRequestEntityResponseBody());
    private RequestEntity< CustomerInfo > getRequestEntityResponseBody(){
     //code
    }
    

    更新

    CustomerInfo customerInfo = new CustomerInfo();
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("MyResponseHeader", "MyValue");
    RequestEntity<CustomerInfo> customerInfoRequestEntity = new ResponseEntity<CustomerInfo>(customerInfo, responseHeaders, HttpStatus.OK);
    PowerMockito.mockStatic(RequestEntity.class);
    when(RequestEntity.post(any(URI.class))).thenReturn(customerInfoRequestEntity);
    

    【讨论】:

    • 你能解释一下为什么你返回了 getRequestEntityResponseBody() 以及你为什么写了那个方法@raviiii1
    • 同一方法可能有多个测试。在这种情况下,可以重用它来返回 RequestEntity,而不是在每个测试中重复创建。如果你在本地创建对象就很好了。
    • 你能给我看一个在本地创建对象/mock 对象的例子吗?我遇到了问题,因为它需要 url 及其模拟测试@raviiii1
    • @ApurvAdarsh ,我已经更新了回复。正如我之前提到的,customerInfoRequestEntity 的创建可以放入一个方法中,以便在其他测试中使用。
    • 我们可以使用响应实体创建请求实体对象吗? RequestEntity customerInfoRequestEntity = new ResponseEntity(customerInfo, responseHeaders, HttpStatus.OK); @raviiii1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2014-08-28
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多