Skip to content
Advertisement

testing code with a “real” Thymeleaf template engine and nothing else

In my Spring Boot project (v2.6), one of my components is using a Thymeleaf template engine to generate content.

I want to unit test my component, but I am struggling because it has a TemplateEngine as a constructor dependency :

public EmailNotifier(JavaMailSender emailSender,TemplateEngine templateEngine) {
  this.emailSender = emailSender;
  this.templateEngine=templateEngine;
}  

I don’t want to mock the TemplateEngine (the test would not have great value), I would prefer to use a “real” (and configured) templateEngine, and make sure that the content is generated as I expect. But I would like my test to be as “low-level” as possible, ie without loading the full application with Spring.

Spring Boot doesn’t have a Thymeleaf “slice” like it has for Jpa or Web tests, but I guess I need something similar to that.

How can I get the minimum Spring magic in my test, so that it’s both a realistic and fast test ?

Advertisement

Answer

This is what I ended up doing :

@SpringBootTest
class EmailNotifierTest {

  //to have Spring Boot manage the thymeleaf config
  @EnableAutoConfiguration
  @Configuration
  static class MinimalConfiguration {
    @Autowired
    TemplateEngine templateEngine;

    @Bean
    public EmailNotifier notifier(){

      JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
      mailSender.setHost("localhost");
      mailSender.setPort(3025);

      return new EmailNotifier(mailSender, templateEngine);
    }
  }
  
  @Autowired
  EmailNotifier myEmailNotifier;


  //tests using myEmailNotifier go here...

}

My object is ready to be used, with a templateEngine configured by Spring, the same way it will be when running in production. I guess we can exclude some auto configurations if needed, to go faster. But in my case I don’t have too many other dependencies available, so the test is still quite fast to run, thanks to the minimal Spring overhead.

Advertisement