模拟ResponseEntity <T>的正确方法是什么?

时间:2020-10-07 22:09:24

标签: java spring junit mockito

我正在编写一个单元测试用例以测试其余服务。似乎我在嘲笑测试用例通过所需要的所有内容,但不幸的是它失败了,我仍然在获得空指针异常

 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());
        }
    }

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

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

谢谢

1 个答案:

答案 0 :(得分:0)

好的。因此,我只添加了一些模拟数据并修改了我的测试用例。终于,它现在可以工作了。

# you have a list with all Tweets ids created with snscrape: all_id_list
# split list in a list of list with 100 ids

id_list = [all_id_list[x:x+100] for x in range(0, len(all_id_list), 100)]

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)

# iterated over the list to get per request 100 tweets over the twitter api
for i in id_list:
     tweets = api.statuses_lookup(list(id_list[i]))

     for tweet in tweets:
          print(tweet.text)