Testing Thymeleaf Template Integration in Spring Boot Examples
This test suite validates the Thymeleaf template integration within a Spring Boot web application. It focuses on testing HTTP endpoints, template rendering, and static resource handling using Spring’s TestRestTemplate.
Test Coverage Overview
Implementation Analysis
Technical Details
Best Practices Demonstrated
ityouknow/spring-boot-examples
spring-boot-web-thymeleaf/src/test/java/com/neo/ThymeleafApplicationTests.java
package com.neo;
import java.net.URI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ThymeleafApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
private int port=8080;
@Test
public void testHome() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("<title>Messages");
assertThat(entity.getBody()).doesNotContain("layout:fragment");
}
@Test
public void testCreate() {
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.set("text", "FOO text");
map.set("summary", "FOO");
URI location = this.restTemplate.postForLocation("/", map);
assertThat(location.toString()).contains("localhost:" + this.port);
}
@Test
public void testCss() {
ResponseEntity<String> entity = this.restTemplate.getForEntity(
"http://localhost:" + this.port + "/css/bootstrap.min.css", String.class);
ResponseEntity<String> response = restTemplate.exchange(
createURLWithPort("/students/Student1/courses"),
HttpMethod.POST, entity, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("body");
}
private String createURLWithPort(String uri) {
return "http://localhost:" + port + uri;
}
}