响应实体执行HTTP GET请求的模拟单元测试用例

时间:2019-02-01 02:27:52

标签: java spring-boot mockito

我正在为执行GET请求(向外部系统查询)的方法之一编写单元测试用例,并接收存储在模型对象中的查询结果,但我无法模拟其余模板交换。需要一些帮助。

下面的代码包括我的方法以及该方法的测试类。

public Car getCarModelDetails(String id) {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", APPLICATION_JSON);

    HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
    ResponseEntity<QueryResultCar> exchange = restTemplate.exchange(
            config.restUrl + "/v" + config.restVersion + /query?q=SELECT + SELECT_COLUMNS
                    + " FROM Car WHERE (Model = '" + id + "')",
            HttpMethod.GET, entity, QueryResultCar.class);

    if (exchange.getStatusCode().equals(HttpStatus.OK)) {
        List<Car> records = exchange.getBody().records;
        if (records != null && records.size() == 1) {
            return records.get(0);
        } else (records == null || records.isEmpty()) {
            return null;
        } 

    } else {
        throw new RuntimeException();
    }
}


private static class QueryResultCar extends QueryResult<Car> {
}

  @Test
public void getCarModelDetails_valid() throws JSONException {   
    String id = null;
    HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
     new ResponseEntity<>("", HttpStatus.OK);
    Mockito.when(restTemplate.exchange(config.restUrl + "/v" + config.restVersion + /query?q=SELECT + SELECT_COLUMNS
                    + " FROM Car WHERE (Model = '" + id + "'), HttpMethod.GET, entity, QueryResultCar.class))
            .thenReturn(response);  

}

2 个答案:

答案 0 :(得分:2)

您需要使用匹配器,并且可能需要使用verify和arg captor来检查所需的所有内容。我可能会对此测试进行划分,因为它有很多断言,但这应该可以帮助您入门。

@RunWith(MockitoJUnitRunner.class)
public class SubjectTest {

@InjectMocks
private CarCar subject;
@Mock
private RestTemplate restTemplate;

@Test
public void getCarModelDetails_valid() throws JSONException {
    String id = "123";
    Config config = new Config();
    when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(QueryResultCar.class)))
            .thenReturn(new ResponseEntity<>(new QueryResultCar(), HttpStatus.OK));

    Car actual = subject.getCarModelDetails(id);

    ArgumentCaptor<HttpEntity> httpEntityArgumentCaptor = ArgumentCaptor.forClass(HttpEntity.class);
    verify(restTemplate).exchange(eq(config.restUrl + "/v" + config.restVersion + "/query?q=SELECT + SELECT_COLUMNS"
            + " FROM Car WHERE (Model = '" + id + "')"), eq(HttpMethod.GET), httpEntityArgumentCaptor.capture(), eq(QueryResultCar.class));
    assertEquals(APPLICATION_JSON_VALUE, httpEntityArgumentCaptor.getValue().getHeaders().get("Accept").get(0));
    assertEquals("Car to string", actual.toString());
}

}

答案 1 :(得分:1)

单元测试方法中的“实体”的对象引用与实际方法不同。您需要为“实体”处理模拟