Spring Boot测试中的Mockito和多个HTTP

安托码

我正在处理的项目遇到很大的问题,我想知道您是否可以帮助我。

我必须使用Mockito执行一些单元测试,所有方法都很棒!直到您以相同的方法有2次对http的调用,而我不知道如何区分它们。

我在测试中有以下内容:

  // -----------------------------------------------------------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个列表,因此测试无法继续。

如果我尝试使用该代码,那么一切都会正常工作并使它正常工作,我遇到的问题是在测试时会克隆列表。

我不知道是否有一种方法可以使模拟的“何时”可以使它们与众不同,因为它使我了解到,当我这样做时,它需要第一时间。

非常感谢您的帮助!

安托码

我找到了解决方案,而不是多次使用key进行呼叫,然后按需要的顺序进行了多次返回(按要求的顺序附加了我的工作方式)

when(restTemplate.exchange(anyString(), any(HttpMethod.class),
            any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenReturn(list).thenReturn(listaMovi);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章