Search code examples
springspring-boot-test

Excluding Configuration class from SpringBootTest


I have a class to configure Kafka under src/main/java:

@Configuration
public class SenderConfig {

    @Value("${spring.kafka.producer.bootstrap-servers}")
    private String bootstrapServers;


    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Bean
    public ProducerFactory<String,Item> producerFactory(){
        log.info("Generating configuration to Kafka key and value");
        Map<String,Object> config = new HashMap<>();
        config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrapServers);
        config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
        return new DefaultKafkaProducerFactory(config);
    }

I have a class under src/test/java to test a repository and I want to exclude this configuration class:

@SpringBootTest(properties = { "spring.cloud.config.enabled=false",
        "spring.autoconfigure.exclude=com.xyz.xyz.config.SenderConfig" })
@Sql({ "/import_cpo_workflow.sql" })
public class WorkflowServiceTest {

    @Autowired
    private WorkflowRep workflowRep;

    @Test
    public void testLoadDataForTestClass() {
        assertEquals(1, workflowRep.findAll().size());
    }
}

Error: Caused by: java.lang.IllegalStateException: The following classes could not be excluded because they are not auto-configuration classes: com.xyz.xyz.config.SenderConfig

How can I exclude this configuration class from my test since I'm not testing Kafka in this moment?


Solution

  • You can declare a SenderConfig property in the test class, annotated as @MockBean (and do nothing with it if you don't need it in the test) and that will effectively override the real one in the test's ApplicationContext and stop the real one from being instantiated by the BeanFactory.

    https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html