从 SpringBootTest 中排除配置 class

Excluding Configuration class from SpringBootTest

我有一个 class 在 src/main/java 下配置 Kafka:

@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);
    }

我在 src/test/java 下有一个 class 来测试存储库,我想排除此配置 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());
    }
}

错误:原因:java.lang.IllegalStateException:无法排除以下 classes,因为它们不是自动配置 classes:com.xyz.xyz.config.SenderConfig

我现在不测试 Kafka,如何从我的测试中排除此配置 class?

尝试使用@ComponentScan排除类。

示例:

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

您可以在测试 class 中声明一个 SenderConfig 属性,注释为 @MockBean(如果您在测试中不需要它,则不使用它)并且将有效地覆盖测试的 ApplicationContext 中的真实对象并阻止真实对象被 BeanFactory 实例化。

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