java - 如何使用 junit 5 (Jupiter) 模拟 RestTemplate 交换
问题描述
我尝试使用以下代码,但在响应正文中我得到了空记录。
请在下面的代码上帮助我。
Java 代码:
public Customer getCustomers(String customerId, String authorization) {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.set("Authorization", authorization);
HttpEntity<Customer> request = new HttpEntity<>(headers);
Map<String, Object> params = new HashMap<>();
params.put("CustomerId", customerId);
String url = "https://localhost:8080/api/customer/{CustomerId}/get";
ResponseEntity<Customer> response = restTemplate.exchange(
url,
HttpMethod.GET,
request,
Customer.class,
params
);
Customer customer = null;
if (response != null && response.getBody() != null) {
customer = response.getBody();
}
return customer;
}
测试代码:
@Test
public void testGetCustomersSuccess() {
Customer customer = new Customer();
customer.setCountryCode("countryCode");
customer.setCreatedFrom("createdFrom");
customer.setCustomerlandline("224153");
customer.setCustomermobile("1522252");
customer.setEmail("email");
customer.setFirstname("firstName");
customer.setFiscalCode("fiscalCode");
customer.setFirstname("lastName");
customer.setId("5");
MultiValueMap<String, String> headers=new LinkedMultiValueMap<>();
headers.set(Authorization,"12152");
ResponseEntity<Customer> response=new ResponseEntity<Customer>(HttpStatus.OK);
when(restTemplate.exchange(Mockito.any(String.class),
Mockito.<HttpMethod> any(),
Mockito.<HttpEntity<Customer>> any(),
Mockito.<Class<Customer>> any(),
Mockito.<String, Object> anyMap()))
.thenReturn(response);
assertEquals(response.getBody(),serviceClientImpl.getCustomers("5", "12152"));
}
解决方案
您需要在响应中设置客户的价值。您在客户对象中设置的值未在任何地方使用。尝试这个:
ResponseEntity<Customer> response=new ResponseEntity<Customer>(customer,HttpStatus.OK);
推荐阅读
- reactjs - 在 react hooks 中生成新的组件类型,如何保持性能?
- php - WooCommerce 添加到购物车,从自定义选择字段中添加第二个产品
- java - 如何在 Java 中更改 JMenu 的字体大小?
- javascript - 当db中的数据被另一台设备更新而没有刷新页面时如何在一台设备上更改vuejs组件数据
- mongodb - 从分组的行中获取字段数
- python - 如何在一行中显示所有绘图图?
- r - 如何修复传单地图中 ggplot 图形的扭曲交互式弹出窗口
- javascript - 在当前选项卡中打开带有修改标题的链接
- r - 在 R 列中减少到 53 类
- javascript - 如何使用 Javascript 停止和启动动画?