如何使用Mockito模拟do While Loop


//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((。这是一种非常糟糕的做法。你不应该阻止反应式代码。

最新更新