在SpringBoot中测试电子邮件服务

时间:2017-03-11 07:20:31

标签: spring spring-mvc spring-boot smtp junit4

我使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎和包作为可执行的JAR文件生成了一个Spring Boot Web应用程序。

使用的技术:

Spring Boot 1.4.2.RELEASE,Spring 4.3.4.RELEASE,Thymeleaf 2.1.5.RELEASE,Tomcat Embed 8.5.6,Maven 3,Java 8

我有这个我要测试的电子邮件服务

@Service
public class MailClient {

    protected static final Logger looger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    private MailContentBuilder mailContentBuilder;

    @Autowired
    public MailClient(JavaMailSender mailSender, MailContentBuilder mailContentBuilder) {
        this.mailSender = mailSender;
        this.mailContentBuilder = mailContentBuilder;
    }

    //TODO: in a properties
    public void prepareAndSend(String recipient, String message) {
        MimeMessagePreparator messagePreparator = mimeMessage -> {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
            messageHelper.setFrom("nunito@calzada.com");
            messageHelper.setTo(recipient);
            messageHelper.setSubject("Sample mail subject");
            String content = mailContentBuilder.build(message);
            messageHelper.setText(content, true);
        };
        try {
            if (looger.isDebugEnabled()) {
                looger.debug("sending email to " + recipient);
            }
            mailSender.send(messagePreparator);
        } catch (MailException e) {
            looger.error(e.getMessage());
        }
    }
}

我已经创建了这个测试类

@RunWith(SpringRunner.class)
public class MailClientTest {

    @Autowired
    private MailClient mailClient;

    private GreenMail smtpServer;

    @Before
    public void setUp() throws Exception {
        smtpServer = new GreenMail(new ServerSetup(25, null, "smtp"));
        smtpServer.start();
    }

    @Test
    public void shouldSendMail() throws Exception {
        //given
        String recipient = "nunito.calzada@gmail.com";
        String message = "Test message content";
        //when
        mailClient.prepareAndSend(recipient, message);
        //then
        String content = "<span>" + message + "</span>";
        assertReceivedMessageContains(content);
    }

    private void assertReceivedMessageContains(String expected) throws IOException, MessagingException {
        MimeMessage[] receivedMessages = smtpServer.getReceivedMessages();
        assertEquals(1, receivedMessages.length);
        String content = (String) receivedMessages[0].getContent();
        System.out.println(content);
        assertTrue(content.contains(expected));
    }

    @After
    public void tearDown() throws Exception {
        smtpServer.stop();
    }

}

但是我在运行测试时遇到了这个错误

Error creating bean with name 'com.tdk.service.MailClientTest': Unsatisfied dependency expressed through field 'mailClient'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tdk.service.MailClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

1 个答案:

答案 0 :(得分:0)

问题是您想要在不提供bean的情况下运行集成测试! 无论何时使用@Autowired,您都需要通过上下文提供自动装配组件所需的bean。 因此,您需要在具有@Configuration注释的测试类中添加静态类。此外,测试类还需要知道必须通过@ContextConfiguration注释使用哪个配置。这里有一个例子:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MailClientTest.ContextConfiguration.class})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MailClientTest {

    @Configuration
    @TestPropertySource(locations = "classpath:application.properties",
            properties ={"my.additiona.property=123"})
    @ComponentScan(basePackages = {"com.tdk.service"})
    public static class ContextConfiguration {
      @Bean
      public JavaMailSender mailSender{
        return ... //create the instance here
      }

      @Bean     
      public  MailContentBuilder mailContentBuilder() {
        return ... //create the instance here
      }
    }
}

无论如何,正如我在评论中已经指出的那样,不要浪费你的时间重新发明轮子。已经有一个图书馆可以为您完成所有这些工作。我在谈论Spring Boot Email Tools。 我认为值得使用该库,并且可能使用新功能为存储库做出贡献,而不是花时间重新实现模板引擎的电子邮件支持。

相关问题