5

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?

Aldo Inácio da Silva
  • 824
  • 2
  • 14
  • 38

2 Answers2

3

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

Chris
  • 1,644
  • 1
  • 11
  • 15
  • 1
    I just had to add another MockBean because I have a bean creation inside SenderConfig that is used by some Controllers. Btw I'm not testing in this moment. – Aldo Inácio da Silva Apr 14 '20 at 12:43
  • 1
    Ah cool, sometimes I have to fiddle about a little bit to facilitate integration testing but MockBean is handy around ConfigurationClasses where you can either mock the whole thing or just mock individual beans – Chris Apr 14 '20 at 13:23
1

Try to use @ComponentScan to exclude classes.

Example:

@ComponentScan(basePackages = {"package1","package2"},
  excludeFilters = {@ComponentScan.Filter(
    type = FilterType.ASSIGNABLE_TYPE,
    value = {SenderConfig.class})
  })
ish
  • 161
  • 7