在Spring Boot中整合Thymeleaf进行单元测试,可以使用Spring Boot Test和Thymeleaf Test库。下面是一个简单的示例,展示了如何编写针对Thymeleaf模板的单元测试:
在pom.xml
文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-testing</artifactId>
<version>3.0.12.RELEASE</version>
<scope>test</scope>
</dependency>
在src/main/resources/templates
目录下创建一个名为example.html
的Thymeleaf模板文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}">Title</title>
</head>
<body>
<h1 th:text="${message}">Hello, World!</h1>
</body>
</html>
在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("<h1>Hello, Thymeleaf!</h1>");
})
);
// 创建测试执行器
TestExecutor testExecutor = new TestExecutor();
testExecutor.setProcessingContextBuilder(new SpringWebProcessingContextBuilder());
testExecutor.setReporter(new ConsoleTestReporter());
// 执行测试序列
testExecutor.executeTestSequence(testSequence);
}
}
在IDE中运行ExampleTemplateTest
类,或者使用Maven命令行工具运行:
mvn test
这将执行单元测试,并验证Thymeleaf模板的输出是否符合预期。