如何使用Mockito模拟Do-While循环?

e4eetjau  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(315)
//Below are the methods  
public Apple getAppleByNameVersion(String server, String appleName, String version) throws SSLException {

    List<Apple> allAppleList = getAllApplesByServer(server);

    for(int i = 0; i < allAppleList.size(); i++){
        if(allAppleList.get(i).getName().equals(appleName) && allAppleList.get(i).getEntityVersion().equals(version)){
            return allAppleList.get(i);
        }
    }
    return null;
}

public List<Apple> getAllApplesByServer(String server) throws SSLException {
    List<Apple> allAppleList = new ArrayList<>();
    List<Apple> appleListByPage = new ArrayList<>();
    int page = 1;
    AppleServerEnum appleServerEnum = AppleServerEnum.getByServer(server);
    String urlApi = appleServerEnum.getUrl();
    do{
        Flux<Apple> apple = webClient.get()
            .uri(urlApi + "?page=" + page)
            .header(HEADER_NAME, HEADER_VALUE)
            .retrieve()
            .bodyToFlux(Strategy.class);
        appleListByPage = apple.collectList().block();
        allAppleList.addAll(appleListByPage);
        page++;

    }while(!appleListByPage.isEmpty());

    return allappleList;
}

//Below is the test
@Test
void get_withSuccess() throws FileNotFoundException, SSLException, JsonProcessingException {
    Apple apple = new Apple();
    Apple apple1 = new Apple();
    List<Apple> allAppleList = new ArrayList<>();
    List<Apple> appleListByPage = Arrays.asList(apple, apple1);
    int page = 1;

    String farmUri = "https://podpc1y-dr3-core.pod-fx.us.dell.com/abre-admin-api/abre/adminapi/v7/strategyscripts";

    Mono<List> mono = mock(Mono.class);

    when(webClientMock.get()).thenReturn(requestHeadersUriSpec);
    when(requestHeadersUriSpec.uri(anyString())).thenReturn(requestBodyMock);
    when(requestBodyMock.header(any(), any())).thenReturn(requestBodyMock);
    when(requestBodyMock.retrieve()).thenReturn(responseMock);
    when(responseMock.bodyToFlux(Strategy.class)).thenReturn(Flux.just(new apple()));
    strategyListByPage=mono.block();

    // act
    appleService.getAllapplesByServer("farm");

    // assert
    verify(webClientMock).get();
    // TODO: add more assertions
}
kr98yfug

kr98yfug1#

你不能模拟一个循环。在你的例子中,模拟webClient。还有一件事,你正在使用block()。这是一个非常糟糕的做法。你不应该阻止React性代码。

相关问题