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;
//User agent string
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(
//Access with GET method
get("/")
//Specify request header
.header(HttpHeaders.USER_AGENT, USER_AGENT))
//Test HTTP status code
.andExpect(status().is2xxSuccessful())
//Test view name
.andExpect(view().name("index"))
//Test model attributes
.andExpect(model().attribute("userName", "Alice"))
//Test Content Type
.andExpect(content().contentType("text/html;charset=UTF-8"))
//Test if the page contains the specified text
.andExpect(content().string(containsString("Alice")));
}
}
Recommended Posts