在测试中,我希望命中一个返回类型列表的端点。目前我有
@Test
public void when_endpoint_is_hit_then_return_list(){
//Given
ParameterizedTypeReference<List<Example>> responseType = new ParameterizedTypeReference<List<Example>>() {};
String targetUrl = "/path/to/hit/" + expectedExample.getParameterOfList();
//When
//This works however highlights an unchecked assignment of List to List<Example>
List<Example> actualExample = restTemplate.getForObject(targetUrl, List.class);
//This does not work
List<Example> actualExample = restTemplate.getForObject(targetUrl, responseType);
//This does not work either
List<Example> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});
//Then
//Assert Results
}
Run Code Online (Sandbox Code Playgroud)
getForObject 方法的问题是 ParameterizedTypeReference 使 getForObject 方法无法解析,因为类型不匹配。
交换方法的问题是类型不兼容。必需的列表,但“交换”被推断为 ResponseEntity:不存在类型变量的实例,因此 ResponseEntity 符合列表
在这种情况下,如何正确使用 ParameterizedTypeReference 来安全地返回我想要的 List 类型?
我正在使用 Mockito 和 JUnit 测试企业级应用程序。这是将产品添加到我拥有的产品 offline-repository-class-test 中的离线存储库类的方法的代码:
@Mock
private InitialData initialData;
@InjectMocks
private ProductRepositoryOffline pro;
@Test
public void testPersistProduct() {
Product product = new Product(0, "", "", "", 0.0, true, "", 0, /*Product type*/null, "", 0, 0);
ArrayList<Product> productList = new ArrayList<Product>();
//productList.add(product);
Mockito.when(initialData.getProducts()).thenReturn(productList);
pro.persistProduct(product);
assertEquals(pro.getProducts().get(0), product);
}
Run Code Online (Sandbox Code Playgroud)
这依赖于类中的以下方法:
它正在测试的方法ProductRepositoryOffline:
@Override
public void persistProduct(Product pr) {
initialData.addProduct(pr);
}
Run Code Online (Sandbox Code Playgroud)
初始数据
private ArrayList<Product> products = new ArrayList<Product>();
public void addProduct(Product product) {
products.add(product);
}
Run Code Online (Sandbox Code Playgroud)
我想问的问题是,pro.persistProduct(product)除非我已经将产品添加到ArrayList,否则不persistProduct …