2017-07-27 70 views
1

在弹簧引导自动配置项目中,有两个emailSender子类:MockEmailSender和TextEmailSender。而在自动配置只有一个mailSender应创建:如何为弹簧引导自动配置进行单元测试

@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错误。我想我的配置设置没有被测试加载。

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

回答

0

我终于解决了。只需将@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; 
    } 
} 
0

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

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

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

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

无论使用哪个配置文件,应该有一个emailSender,因为我在自动配置中使用了'@ConditionalOnMissingBean(MailSender.class)'。 – bresai