簡體   English   中英

Spring Boot測試中的Mockito和多個HTTP

[英]mockito and multiple HTTP in Spring Boot test

我正在處理的項目遇到很大的問題,我想知道您是否可以幫助我。

我必須使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM