【问题标题】:Mockito is not working for meMockito 不适合我
【发布时间】:2018-01-30 10:15:47
【问题描述】:

案例 1:在我的服务类中调用下面的 Employee 类

ResponseEntity<Employee> response = restTemplate.exchange(url, HttpMethod.GET, entity,Employee.class);

下面在我的测试类中使用,响应是给 emp 对象。

Employee emp = new Employee();
ResponseEntity<Employee> responseEntity = new ResponseEntity<Employee>(emp,HttpStatus.ACCEPTED);
when(restTemplate.exchange(Mockito.anyString(), Mockito.any(), Mockito.any(),Mockito.<Class<Employee>>any())).thenReturn(responseEntity);

案例 2:在我的服务类中调用下面的调用,其中 Employee 是数组

ResponseEntity<Employee[]> response = restTemplate.exchange(url, HttpMethod.GET, entity,Employee[].class); 

我在我的 junit 测试中使用下面。但得到的响应为空。

ResponseEntity<Employee[]> responseEntity = new ResponseEntity<Employee[]>(emp,HttpStatus.ACCEPTED);
when(restTemplate.exchange(Mockito.anyString(), Mockito.any(), Mockito.any(),Mockito.<Class<Employee[]>>any())).thenReturn(responseEntity);

在情况 (1) 中,我使用的是 Employee,而在情况 (2) 中,我使用的是 Employee[]。当Employee[] 用于我的服务和测试时,我得到null response(ResponseEntity obj),但是当我仅在服务和测试中使用Employee 时,我得到带有emp(存根或虚拟)的ResponseEntity 对象。

请帮忙解释一下为什么我在情况 (2) 中得到空值。

【问题讨论】:

    标签: java rest mockito junit4


    【解决方案1】:

    使用这个:

    ResponseEntity<Employee[]> responseEntity = new ResponseEntity<Employee[]>(emp,HttpStatus.ACCEPTED);
    when(restTemplate.exchange(Mockito.anyString(), Mockito.any(), Mockito.any(),Mockito.<Class<Employee[]>>anyObject())).thenReturn(responseEntity);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2011-01-05
      • 2011-12-23
      • 2012-04-01
      • 2011-05-02
      • 2012-12-07
      • 2012-05-04
      相关资源
      最近更新 更多