Home > Software design >  How can I Mock CompletableFuture in Java
How can I Mock CompletableFuture in Java

Time:11-17

The calls in API:

        CompletableFuture<Beneficiary> beneficiaryCompletableFuture =
            CompletableFuture.supplyAsync(() ->
                    beneficiaryService.validateAndGetCustomer(dto.getBeneficiary()), forkJoinPool);


    CompletableFuture<List<Product>> productsCompletableFuture =
            CompletableFuture.supplyAsync(() ->
                    productService.validateAndGetProducts(dto.getProductCodeList()), forkJoinPool);

When forkJoinPool is a Spring Configuration:

@Configuration
public class ForkJoinConfig {

    @Bean
    public ForkJoinPool getForkJoinPool(){
        return new ForkJoinPool();
    }
}

When i try to test this in Junit the call is stucked, the test does not work...

stucked_test

I really don't know can i simple Mock a CompletableFuture.supplyAsync and identify what is Product or what is Beneficiary...

CodePudding user response:

I created a component with has the same method of original static class, so when you need to mock, you can use @Mock.

@Component
public class ApplicationCompletableFuture {
    public <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                ForkJoinPool forkJoinPool) {
        return CompletableFuture.supplyAsync(supplier, forkJoinPool);
    }
}
CompletableFuture<Pet> branchCompletableFuture =
        applicationCompletableFuture.supplyAsync(() -> petService.validatePet(dto.getPetCode), forkJoinPool);
when(applicationCompletableFuture.supplyAsync(any(),any()))
        .thenReturn(CompletableFuture.completedFuture(pet));
  • Related