我正在使用以下 bean 解析 Thymeleaf 模板:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@Service
public class ThymeleafProcessor {
private final TemplateEngine templateEngine;
@Autowired
public ThymeleafProcessor(TemplateEngine templateEngine) {
this.templateEngine = templateEngine;
}
public String process() {
final var templateResolvers = templateEngine.getTemplateResolvers();
System.out.println(templateResolvers);// Collection with one SpringResourceTemplateResolver
String process = templateEngine.process("test.html", new Context());
System.out.println(process); //Prints "Hello World"
return process;
}
}
模板位于 src/main/resources/templates 中,如下所示:
Hello World
到目前为止一切正常。
现在我想为 bean 编写一个单元测试,但这不起作用:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.thymeleaf.TemplateEngine;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {
ThymeleafProcessor.class,
TemplateEngine.class,
})
@EnableConfigurationProperties
class ThymeleafProcessorTest {
@Autowired
private ThymeleafProcessor thymeleafProcessor;
@Autowired
private TemplateEngine templateEngine;
@Test
void doTest() {
System.out.println(templateEngine.getTemplateResolvers().size()); //this will return 0 in the test
var result = thymeleafProcessor.process();
assertEquals("Hello World", result);
}
}
插入预期的字符串“Hello World”,返回字符串“test.html”。问题似乎是没有可用的模板解析器。
需要如何配置测试才能测试 Thymeleaf 模板?
那些与 thymeleaf 相关的 beans 由
ThymeleafAutoConfiguration
自动配置,由任何用 @EnableAutoConfiguration
注释的配置类启用。
@SpringBootApplication
有这个@EnableAutoConfiguration
,所以当你使用正常方式启动应用程序时,ThymeleafAutoConfiguration
生效并定义相关的thymeleaf beans。
但是现在在 test 中,您只需指定使用
ThymeleafProcessor
和 TemplateEngine
作为配置类来启动 spring 上下文。不涉及 @SpringBootApplication
/ @EnableAutoConfiguration
,因此 ThymeleafAutoConfiguration
不生效。
您可以通过使用
ThymeleafAutoConfiguration
显式导入 @ImportAutoConfiguration
来修复它:
@SpringBootTest(classes = {ThymeleafProcessor.class})
@ImportAutoConfiguration(ThymeleafAutoConfiguration.class)
class ThymeleafProcessorTest {
}
另外,我整理了一下代码:
@ExtendWith(SpringExtension.class)
不是必需的,因为它已由 @SpringBootTest
定义
您无需在
TemplateEngine
中定义 @SpringBootTest
,因为它将由 ThymeleafAutoConfiguration
定义
很可能
@EnableConfigurationProperties
也不需要