Thymeleaf 3 с Spring Boot 2, невозможно обработать шаблон - PullRequest
0 голосов
/ 05 июня 2018

Перед чтением, пожалуйста, обратите внимание, что я новичок в Thymeleaf, Spring и Mockito.Так что я ожидаю, что я совершил какую-то любительскую ошибку.

Я пишу код для отправки электронных писем с использованием HTML-шаблонов тимилиста.Я смотрел на различные учебники в Интернете и пытался все настроить.Я думаю, что мои настройки в порядке, однако, когда я пишу тест, чтобы проверить, обрабатывается ли шаблон, я получаю «null» вместо некоторой формы строки.

Я поместил файл шаблона в оба файла: src / main / resources / templates и src / test / resources / templates

Имя файла: email.html

Ниже приведен мой код для настройки механизма шаблонов и распознавателя.

    @Configuration
    public class SpringMailConfig{
...
    @Bean
        public SpringTemplateEngine springTemplateEngine(){
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            templateEngine.addTemplateResolver(htmlTemplateResolver());
            templateEngine.setTemplateEngineMessageSource(emailMessageSource());
            return templateEngine;
        }

        @Bean
        public SpringResourceTemplateResolver htmlTemplateResolver() {
            SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
            templateResolver.setPrefix("/templates/");
            templateResolver.setSuffix(".html");
            templateResolver.setTemplateMode(TemplateMode.HTML);
            templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
            return templateResolver;
        }
...
    }

Это класс, в котором я хочу обработать шаблон, я показываю только то, что считаю важным для этого вопроса.

@Component
public class EmailServiceHelper {

    @Autowired
    public SpringTemplateEngine springTemplateEngine;

   private  Context prepareContext(Locale locale, Map<String, Object> contextMap){
        final Context context = new Context(locale);
        context.setVariables(contextMap);
        return context;
    }

    //returns as a string the template with the custom values inserted
    private String returnHtmlContent(String templatePath, Locale locale, Map<String,Object> map){
        Context ctx = prepareContext(locale, map);
        return springTemplateEngine.process(templatePath, ctx);
    }

}

И это тестовый класс (часть), в котором я получаю сообщение об ошибке, что springTemplateEngine.process (templatePath, ctx) возвращает ноль.

@RunWith(MockitoJUnitRunner.class )
public class EmailServiceHelperTest {
@Mock
    SpringTemplateEngine springTemplateEngine;

    @Mock
    SpringResourceTemplateResolver springResourceTemplateResolver;
@InjectMocks
EmailServiceHelper helper;

   @Before
    public void setup(){

        MockitoAnnotations.initMocks(this);
        helper = new EmailServiceHelper();
        helper.springTemplateEngine = springTemplateEngine;
    helper.springTemplateEngine.setTemplateResolver(springResourceTemplateResolver);
    }

@Test
    public void testTemplateMessageHasContent(){
        try {
            Locale locale = new Locale("en");
            Map<String, Object> contextMap = new HashMap<>();
            contextMap.put("name", "Test name");
            MimeMessage message = helper.prepareMimeMessage(mail, mailSender, contextMap, "email", locale);
            assertNotNull(message.getContent());
        }catch (MessagingException | IOException e){
            e.printStackTrace();
            fail("Testing if template message has content failed!");
        }
    }
}

Thisтак выглядит мой шаблон электронной почты.

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>TEMPLATE</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1 th:text="${name}">Hello, Static Person!</h1>

</body>
</html>

1 Ответ

0 голосов
/ 07 июня 2018

Я понял это.Как и предполагалось, это была ошибка новичка с моей стороны.Так как я издевался над механизмом шаблонов, мне пришлось создавать в моем тесте методы, которые обрабатывают шаблон.Тогда я сделал:

when(mockObject.processTemplate()).thenReturn(localProcessTemplateMethod();
...