繁体   English   中英

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

[英]How do I mock Do-While Loop using Mockito?

//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
}

你不能模拟一个循环。 在您的情况下模拟 webClient。 还有一件事,您正在使用 block()。 这是一个非常糟糕的做法。 您不应该阻止响应式代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM