我正在为我的一个方法编写单元测试用例,该方法执行 GET Request(查询到外部系统),并接收我存储在模型对象中的查询结果,我无法模拟其余的模板交换。需要一些帮助。
下面的代码包括我的方法以及该方法的测试类。
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);
}
您需要使用匹配器,并且可能需要使用验证和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());
}
}
单元
测试方法中"实体"的对象引用与实际方法不同。您需要处理"实体"的模拟