【问题标题】:What is the proper way of mocking ResponseEntity<T>?模拟 ResponseEntity<T> 的正确方法是什么?
【发布时间】:2020-10-07 22:09:24
【问题描述】:

我正在编写一个单元测试用例来测试其余的服务。似乎我在嘲笑测试用例通过所需的一切,但不幸的是它失败了,我仍然在

处收到空指针异常
 when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                any(HttpMethod.class),
                any(),
                ArgumentMatchers.<Class<RateResponse>>any()))
                .thenReturn(serviceResponse);

另外,我无法在响应中传递数据(老实说我不知道​​为什么)

RateServiceTest .class

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class RateServiceTest {

    @Mock
    private RateResponse rateResponse;

    @InjectMocks
    private RateService rateService = new RateService();

    @Mock
    private RestTemplate restTemplate;

    @BeforeAll
    public void setUp() throws IOException {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testRateService() throws Exception {
        ResponseEntity<RateResponse> serviceResponse = new ResponseEntity<>(HttpStatus.OK);

        Rate rate1 = new Rate();
        rate1.setOriginId("0100");
        rate1.setDestinationId("0200");

        Rate rate2 = new Rate();
        rate2.setOriginId("0300");
        rate2.setDestinationId("0400");

        List<Rate> rateList = new ArrayList<>();
        rateList.add(rate1);
        rateList.add(rate2);

        when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                any(HttpMethod.class),
                any(),
                ArgumentMatchers.<Class<RateResponse>>any()))
                .thenReturn(serviceResponse);
        when(rateService.mapResponseToRows(any(RateResponse.class))).thenReturn(rateList);
        List<Rate> rateResponse = rateService.getRates();

        assertNotNull(rateResponse);

    }
}

RateResponse.class 它是一个简单的 pojo 类

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "status", "data" })
public class RateResponse {

    @JsonProperty("status")
    private String status;

    @JsonIgnore
    private Object data;

    @JsonProperty("status")
    public String getStatus() {
        return status;
    }

    @JsonProperty("status")
    public void setStatus(String status) {
        this.status = status;
    }

    @JsonProperty("data")
    public Object getData() {
        return data;
    }

    @JsonProperty("data")
    public void setData(Object data) {
        this.data = data;
    }

}

getRates 方法

public List<Rate> getRates() {
        ResponseEntity<RateResponse> response;
        try{
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", computeAuthHeader());
            HttpEntity<Object> entity = new HttpEntity<>(headers);
            response =  restTemplate.exchange(rateURL, HttpMethod.GET, entity, RateResponse.class);
            List<Rate> rateList = mapResponseToRows(response.getBody());
            LOGGER.info("Response from RateService : " + response.getBody().toString());
            return rateList ;
        }
        catch(RateAccessException exception) {
            throw new RateAccessException(exception.getMessage());
        }
    }

而服务只是另一个从端点获取数据的标准服务。

我正在关注堆栈溢出和谷歌上可用的一些线程和其他解决方案,但到目前为止它们都没有工作。我想知道我是否没有正确地模拟所有必需的依赖项,或者我弄乱了我的数据类型,或者在编写测试用例时我是否完全错过了其他一些东西。

谢谢

【问题讨论】:

  • 请发布您的rateService.getRates() mehtod
  • 嗨@haoyuwang我用getRates方法更新了问题
  • 你确定吗?我没看到。
  • 是的,我的网络连接出了点问题,很抱歉!
  • 我建议使用wiremock.org,而不是尝试自己模拟 API 调用。

标签: java spring junit mockito


【解决方案1】:

好的。所以我只是添加了一些模拟数据并稍微修改了我的测试用例。最后,它现在可以工作了。

  @Test
    public void testRateService1() throws Exception
    {
        RateResponse response = new RateResponse();
        List<Map<String, String>> rowList = new ArrayList<>();
        Map<String, String> rowMap = new HashMap<>();
        rowMap.put("ORIGIN_ID", "123");
        rowMap.put("DESTINATION ID", "DEST1");
        rowList.add(rowMap);
        Map<String, Object> rowsMap = new HashMap<>();
        rowsMap.put("rows", rowList);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("query", rowsMap);
        response.setData(dataMap);
        response.setStatus("success");

        ResponseEntity<RateResponse> templateResponse = new ResponseEntity<>(response, HttpStatus.OK);
        
        when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                any(HttpMethod.class),
                any(),
                ArgumentMatchers.<Class<RateResponse>>any()))
               .thenReturn(templateResponse);

        List<Rate> rateList = rateService.getRates();
        Assert.assertEquals(1, rateList.size());
        Assert.assertEquals("DEST1", rateList.get(0).getDestinationId());
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2018-10-13
    • 1970-01-01
    相关资源
    最近更新 更多