import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FooBarController {
@GetMapping("/")
public ModelAndView topPage(ModelAndView mav) {
mav.setViewName("index");
mav.addObject("userName", "Alice");
return mav;
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>My App</title>
</head>
<body>
<p id="user-name" th:text="${userName}"></p>
</body>
</html>
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@SpringBootTest
@AutoConfigureMockMvc
public class FooBarControllerTest {
@Autowired
private MockMvc mockMvc;
//Chaîne d'agent utilisateur
private static final String USER_AGENT =
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_0 like Mac OS X) " +
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 " +
"Mobile/15E148 Safari/604.1";
@Test
public void testTopPage() throws Exception {
this.mockMvc.perform(
//Accès avec la méthode GET
get("/")
//Spécifier l'en-tête de la demande
.header(HttpHeaders.USER_AGENT, USER_AGENT))
//Tester le code d'état HTTP
.andExpect(status().is2xxSuccessful())
//Nom de la vue de test
.andExpect(view().name("index"))
//Attributs du modèle de test
.andExpect(model().attribute("userName", "Alice"))
//Type de contenu de test
.andExpect(content().contentType("text/html;charset=UTF-8"))
//Tester si la page contient le texte spécifié
.andExpect(content().string(containsString("Alice")));
}
}
Recommended Posts