java - Spring Boot 测试中的 mockito 和多个 HTTP
问题描述
我正在处理的一个项目遇到了一个大问题,我想知道你是否可以帮助我。
我必须使用 mockito 执行一些单元测试,所有方法都很棒!直到您以相同的方法对 http 进行了 2 次调用,而我不知道如何区分它们。
我在测试中有以下内容:
// -----------------------------------------------------------services
@InjectMocks
private SandboxAccountService accountService;
@InjectMocks
private SandboxBalancesService balancesService;
@InjectMocks
private SandboxMovementsService movementService;
@Mock
private RestTemplate restTemplate;
@Mock
private RestTemplate restTemplateMovimientos;
@Test
public void test_movementsServiceImpl() throws Exception {
//LLAMADA A LISTA DE Account
List<Account> accountList = new ArrayList<>();
accountList.add(account);
accountList.add(account2);
ResponseEntity<List<Account>> list = new ResponseEntity<List<Account>>(accountList, HttpStatus.OK);
// FIRST HTTP CALL
when(restTemplate.exchange(anyString() , any(HttpMethod.class),
any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenReturn(list);
//LLAMADA A LISTA DE MOVIMIENTOS
listMovent.add(movement);
listMovent.add(movementDos);
ResponseEntity<List<Movement>> listaMovi = new ResponseEntity<List<Movement>>(listMovent, HttpStatus.OK);
// Second HTTP CALL
when(restTemplateMovimientos.exchange(anyString() , any(HttpMethod.class),
any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenReturn(listaMovi);
try {
AccountsMovementsResponse accountsMovementsResponse = movementService.getMovements(accountsMovementsRequest,
AUTORIZATHION_TOKEN, language);
} catch (Exception e) {
}
}
当调试为我正确且一切顺利地完成列表但当他切换到服务时
//// This its a primary http ( Account)
ResponseEntity<List<Account>> exchange = restTemplate.exchange(sandboxAccountURL + userId, HttpMethod.GET,entity,
new ParameterizedTypeReference<List<Account>>() {
});
// This list its Account CORRECT
List<Account> lista=exchange.getBody();
// code.....
// This its a second http ( movement )
ResponseEntity<List<Movement>> movementList = restTemplate.exchange(GenerateUrl, HttpMethod.GET,entity,
new ParameterizedTypeReference<List<Movement>>() {
});
// This list should be moves, but it's a list of accounts.
List<Movement> listMovement= movementList.getBody();
我的大问题是,我没有 2 个不同的列表,而是有 2 个列表,因此测试无法继续。
如果我尝试代码一切正常并使其正常工作,我遇到的问题是在测试时它会克隆列表。
我不知道是否有办法让模拟的“何时”可以使它们变得不同,因为它让我明白当我这样做时它需要第一个。
非常感谢您的帮助!
解决方案
我找到了解决方案,而不是使用何时可以拨打一个电话,然后按照您需要的顺序多次返回,而不是多次使用密钥,并附上我工作方式的答案
when(restTemplate.exchange(anyString(), any(HttpMethod.class),
any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenReturn(list).thenReturn(listaMovi);
推荐阅读
- django - 覆盖 django 序列化程序或模型创建方法
- javascript - 阻止用户在没有警报的情况下退出无模式窗口
- r - 使用 R 中的 XML 包使用命名空间解析 XML
- facebook - 无需成为管理员即可获取 Facebook 群组帖子
- python - 简单的python转置(到0?)
- python - 获取具有最大特定值的整行,Pandas
- ruby-on-rails - 获取 lat/lng 所在区域的最有效方法是什么?
- jersey - Jersey JAX-RS 应用程序返回 404
- audio - 将音频从 java 服务器实时流式传输到 Android 客户端
- python - 获取 Pandas 中每一天的上个月平均值