Search code examples
spring-bootunit-testingmockitospring-boot-test

Spring-Boot | Test Service Containing Call to @Async Method


Want to Unit Test a Service that contains call to a @Aysnc method which return CompletableFuture Object.But the future object is always null (during testing) causing NullPointerException.

future.get() causes the error

Test Code

@RunWith(MockitoJUnitRunner.class)
public class ContainerValidatorTest {

    @Mock
    QueryGenerator queryGenerator;

    @Mock
    SplunkService splunkService;

    @InjectMocks
    private ContainerValidatorImpl containerValidatorImpl;

    @Test
    public void validateContainerTestWithNullData(){
        CacheItemId cacheItemId = null;
        String container = null;
        assertFalse(containerValidatorImpl.validateContainer(cacheItemId,container));
    }
}

Service Code

@Override
    public boolean validateContainer(CacheItemId cacheItemId, String container) {
        Query query = queryGenerator.getUserDetailsFromCacheInfoQuery(cacheItemId);
        String response;
        try {
            CompletableFuture<String> future = splunkService.doExecuteQuery(query);
            response = future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error While Fetching User Details : "+ e.getLocalizedMessage());
        }
        System.out.println(response);
        JsonArray jsonArray = new JsonParser().parse(response).getAsJsonArray();
        if(!jsonArray.isJsonNull()) {
            return jsonArray.get(0).getAsJsonObject().get("TAG").getAsString().equalsIgnoreCase(container);
        }
        throw new RuntimeException("Not Able to Find UserDetails");
    }


Solution

    • You haven’t set any expectations on splunkService mock.
    • Then you call doExecuteQuery on the mock instance
    • With no expectations for the method call, Mockito returns default value for the method return type (null for Objects)

    To fix, record your expectations with when and thenReturn

    Update

    @Test
    public void validateContainerTestWithNullData(){
        CacheItemId cacheItemId = null;
        String container = null;
        when(splunkService.doExecuteQuery(any())).thenReturn(CompletableFuture.completedFuture("completedVal"));
        assertFalse(containerValidatorImpl.validateContainer(cacheItemId,container));
    }