我正在发送一封带有thymeleaf模板引擎的邮件。当我没有使用thymeleaf时,邮件单元测试运行得很好,但是在我添加了thymeleaf之后,测试一直给我NullPointerException。下面是我从EmailService中得到的代码:
private JavaMailSender javaMailSender;
private TemplateEngine templateEngine;
public EmailServiceImpl(JavaMailSender javaMailSender, TemplateEngine templateEngine){
this.javaMailSender = javaMailSender;
this.templateEngine = templateEngine;
}
@Override
public void sendEmail(Employee employee,String email) throws MessagingException {
Context context = new Context();
context.setVariable("employee",employee);
String process = templateEngine.process("/email",context);
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper;
helper = new MimeMessageHelper(message, true);
helper.setTo(email);
helper.setSubject("Hello "+employee.getName());
helper.setText(process,true);
javaMailSender.send(message);
}
这是我的测试:
@Autowired
TemplateEngine templateEngine;
static Context context;
@Mock
private JavaMailSender javaMailSender;
@InjectMocks
private EmailServiceImpl emailServiceImpl;
private MimeMessage mimeMessage;
private MimeMessageHelper helper;
private String email;
Employee employee;
String process;
@BeforeEach
public void setUp() throws MessagingException {
employee = new Employee("John Smith",
20.0,"AB243", "A","B",
LocalDateTime.now().plusDays(2),20);
mimeMessage = new MimeMessage((Session)null);
email = "someone@gmail.com";
context = new Context();
process = templateEngine.process("/email",context);
helper.setText(process,true);
}
@Test
public void emailTest() throws MessagingException {
when(javaMailSender.createMimeMessage()).thenReturn(mimeMessage);
String recipient = email;
emailServiceImpl.sendEmail(employee,email);
assertEquals(recipient, mimeMessage.getRecipients(MimeMessage.RecipientType.TO)[0].toString());
}
所以我试着自动安装模板引擎,我试着初始化它,我试着设置助手属性,但是什么都不起作用。有人知道如何解决这个问题吗?谢谢!
1条答案
按热度按时间zazmityj1#
这似乎是由于process方法是final的,它并不总是能很好地与mockito一起工作。
1.创建 Package 类a here
1.使用此处描述的
mock-maker-inline
方法我尝试了第二种方法,当我在TemplateEngine上使用
@Mock
时,它非常适合我,例如: