在Spring Boot中测试时注入MailClient

时间:2017-03-15 21:00:35

标签: spring spring-mvc spring-boot dependency-injection junit4

我运行应用程序时运行良好的这些类。

@Service("bookManager")
public class BookManagerImpl implements BookManager {

    private MailClient mailClient;

..

}

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

}

我想创建一个ServiceConfig用于测试目的,但我不知道如何实例化MailClient类,因为没有默认构造函数,构造函数MailClient()未定义

@Configuration
public class ServiceConfig {

    @Bean
    public  SmsService smsService() {
        return new AWSSMSSender();
    }

    @Bean
    public  MailClient mailClient() {
        return new MailClient();
    }
}

使用建议的解决方案:

 return new MailClient(null, null) {
        @Override
        public void prepareAndSend(String recipient, String message)
        {
            // do nothing
        }
    };

我收到了这个错误:

    No qualifying bean of type 'org.springframework.mail.javamail.JavaMailSender' available: expected at least 1 bean which qualifies as autowire candidate. 
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

3 个答案:

答案 0 :(得分:1)

您可以使用GreenMail在Spring Boot中测试您的电子邮件功能

您可以参考以下链接:http://dolszewski.com/spring/sending-html-mail-with-spring-boot-and-thymeleaf/

答案 1 :(得分:0)

你应该使用Stubbing。

存根方法易于使用,并且不涉及单元测试的额外依赖性。基本技术是将协作者实现为具体类,这些类只展示了被测试类所需的协作者整体行为的一小部分。作为示例,考虑服务实现正在测试的情况。

答案 2 :(得分:0)

这取决于您想要做什么,在测试中发送电子邮件(可能使用测试smpt服务器)或只是模拟发送。在第二种情况下,您可以将MailClient子类化为 return new MailClient(null, null) { @Override public void prepareAndSend(String recipient, String message) { // do nothing } }; 中的任何内容,然后使用它的实例。

erlang