Search code examples
javaunit-testingjunitjunit5

Unit coverage for Lambda expresssion in Java


I am trying to cover method which looks like

  protected SessionBuilderConfigurer getSessionBuilderConfigurer() {
    return cqlSessionBuilder -> {
        ProgrammaticDriverConfigLoaderBuilder programmaticDriverConfigLoaderBuilder;
   
        programmaticDriverConfigLoaderBuilder = getCassandraWithoutSslConfiguration();//Local method

        DriverConfigLoader driverConfigLoader = programmaticDriverConfigLoaderBuilder.build();
        return cqlSessionBuilder
            .withConfigLoader(driverConfigLoader)
            .withAuthCredentials(properties.getUsername(), properties.getPassword());
    };
  }

This is not at all getting covered in JUnit.

JUnit:


//Class level
@ExtendWith(MockitoExtension.class)

@InjectMocks WaausCassandraConfiguration configuration;


//Inside method
Assertions.assertNotNull(configuration.getSessionBuilderConfigurer());

Solution

  • The getSessionBuilderConfigurer() creates a SessionBuilderConfigurer object with the lambda is the implementation of some method (possibly SessionBuilderConfigurer.configure()).

    If you want to execute the code in the lambda you need to execute that method:

    CqlSessionBuilder sessionBuilder = mock(CqlSessionBuilder.class);
    // the following line create the SessionBuilderConfigurer
    SessionBuilderConfigurer configurer = configuration.getSessionBuilderConfigurer();
    // the following line calls the lambda
    configurer.configure(sessionBuilder);
    
    // now you need to assert that the correct methods on the sessionBuilder have been called