首页 > 解决方案 > Spring Boot 测试:未加载 JavaMailSender 属性

问题描述

我有一个 JUnit5 单元测试来测试我的 Spring bean 的 sendig 电子邮件。我使用spring-boot-starter-parent 2.5.0及其spring-boot-starter-mail作为依赖项。

在我的/src/test/resources目录中,我有一个application.properties包含spring.mail属性的文件。当我运行测试时,bean 被实例化并自动装配,但没有加载属性。javaMailProperties教室里面JavaMailSender是空的。

我不想使用@SpringBootTest,因为 Spring 会尝试设置所有自动配置的 bean,这些 bean 对于某些 DB 数据源失败。但它应该以这种方式工作。我错过了什么?不MailSender支持自动装配属性吗?

@ExtendWith(SpringExtension.class)
@TestPropertySource("classpath:application.properties")
public class EmailClientTest
{
    @TestConfiguration
    static class EmailClientTestConfiguration
    {
        @Bean
        public MailSender emailSender() {
            return new JavaMailSenderImpl();
        }
    
        @Bean
        public EmailClient emailClient(MailSender emailSender) {
            return new EmailClient(emailSender);
        }
    }

    @Autowired
    private EmailClient emailClient;

    @Test
    void sendEmail() {
        //...
    }
}

标签: spring-bootjunit5spring-boot-test

解决方案


推荐阅读