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?

Upvotes: 6

Views: 16163

Answers (2)

Chris
Chris

Reputation: 1804

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

Upvotes: 5

ish
ish

Reputation: 171

Try to use @ComponentScan to exclude classes.

Example:

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

Upvotes: 1

Related Questions