在Spring Boot中整合Thymeleaf进行单元测试,可以使用Spring Boot Test和Thymeleaf Test库。下面是一个简单的示例,展示了如何编写针对Thymeleaf模板的单元测试:
- 添加依赖
在pom.xml
文件中添加以下依赖:
org.springframework.boot spring-boot-starter-test test org.thymeleaf thymeleaf-testing 3.0.12.RELEASE test
- 创建Thymeleaf模板
在src/main/resources/templates
目录下创建一个名为example.html
的Thymeleaf模板文件:
Title Hello, World!
- 编写单元测试
在src/test/java
目录下创建一个名为ExampleTemplateTest.java
的测试类:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import org.thymeleaf.testing.templateengine.context.web.SpringWebProcessingContextBuilder; import org.thymeleaf.testing.templateengine.engine.TestExecutor; import org.thymeleaf.testing.templateengine.report.ConsoleTestReporter; import org.thymeleaf.testing.templateengine.resource.ClassPathTemplateResource; import org.thymeleaf.testing.templateengine.testable.ITest; import org.thymeleaf.testing.templateengine.testable.ITestSequence; import org.thymeleaf.testing.templateengine.testable.Test; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource(properties = { "spring.thymeleaf.prefix=classpath:/templates/" }) public class ExampleTemplateTest { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test public void testExampleTemplate() { // 创建测试序列 ITestSequence testSequence = new TestSequence( new Test("Example Test", new ClassPathTemplateResource("templates/example.html", null), Collections.singletonMap("message", "Hello, Thymeleaf!"), (context, result) -> { assertThat(result.getRenderedOutput()) .contains("Hello, Thymeleaf!
"); }) ); // 创建测试执行器 TestExecutor testExecutor = new TestExecutor(); testExecutor.setProcessingContextBuilder(new SpringWebProcessingContextBuilder()); testExecutor.setReporter(new ConsoleTestReporter()); // 执行测试序列 testExecutor.executeTestSequence(testSequence); } }
- 运行测试
在IDE中运行ExampleTemplateTest
类,或者使用Maven命令行工具运行:
mvn test
这将执行单元测试,并验证Thymeleaf模板的输出是否符合预期。