如何为spring boot自动配置进行单元测试

如何为spring boot自动配置进行单元测试,spring,unit-testing,spring-boot,Spring,Unit Testing,Spring Boot,在spring引导自动配置项目中,有两个emailSender子类:MockEmailSender和TextEmailSender。在自动配置中,只应创建一个邮件发件人: @Bean @ConditionalOnMissingBean(MailSender.class) @ConditionalOnProperty(name="spring.mail.host", havingValue="foo", matchIfMissing=true) public MailSender mockMail

在spring引导自动配置项目中,有两个emailSender子类:MockEmailSender和TextEmailSender。在自动配置中,只应创建一个邮件发件人:

@Bean
@ConditionalOnMissingBean(MailSender.class)
@ConditionalOnProperty(name="spring.mail.host", havingValue="foo", matchIfMissing=true)
public MailSender mockMailSender() {

    log.info("Configuring MockMailSender");       
    return new MockMailSender();
}

@Bean
@ConditionalOnMissingBean(MailSender.class)
@ConditionalOnProperty("spring.mail.host")
public MailSender smtpMailSender(JavaMailSender javaMailSender) {

    log.info("Configuring SmtpMailSender");       
    return new SmtpMailSender(javaMailSender);
}
以下是我的单元测试代码:

@SpringBootApplication
public class LemonTest implements ApplicationContextAware{
    private ApplicationContext context;

    public static void main(String[] args){
        SpringApplication.run(LemonTest.class, args);
        System.out.println("haha");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}


@RunWith(SpringRunner.class)
@SpringBootTest
public class InitTest {
    @Autowired
    private MailSender mailSender;

    @Test
    public void test(){
        assertNotNull(mailSender);
    }
}
并且属性是

spring.mail.host=foo
spring.mail.port=587
spring.mail.username=alert1
spring.mail.password=123456
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
根据我的自动配置,只应初始化MockEmailSender, 但是这两个emailSender bean都是创建的,所以在运行单元测试时会抛出多个bean错误。我猜测试没有加载我的配置设置

@ActiveProfiles({ "test", "multipleemail" })

那么如何在测试中包括自动配置呢?测试自动配置的最佳实践是什么?

我总是使用单独的“配置文件”创建多个测试,以控制加载/设置的内容,并在测试上设置活动配置文件

@ActiveProfiles({ "test", "multipleemail" })
然后,您的测试将确保预期结果(上下文中有多个电子邮件提供商等)。 如果需要单独的属性,可以导入属性。我在src/test中专门为我的单元测试存储了一个

@PropertySource({ "classpath:sparky.properties" })

我终于解决了。只需将
@Import(LemonAutoConfiguration.class)
添加到应用程序中

@SpringBootApplication
@Import(LemonAutoConfiguration.class)
public class LemonTest implements ApplicationContextAware{
    private ApplicationContext context;

    public static void main(String[] args){
        SpringApplication.run(LemonTest.class, args);
        System.out.println("haha");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}

无论使用哪种配置文件,都应该有一个emailSender,因为我在自动配置中使用了
@ConditionalOnMissingBean(mailssender.class)
。有人投了反对票,但对于非spring自动配置,这对我来说是个好办法