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;
// ユーザーエージェント文字列
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(
// GET メソッドでアクセス
get("/")
// リクエストヘッダを指定
.header(HttpHeaders.USER_AGENT, USER_AGENT))
// HTTP ステータスコードをテスト
.andExpect(status().is2xxSuccessful())
// ビュー名をテスト
.andExpect(view().name("index"))
// モデルの属性をテスト
.andExpect(model().attribute("userName", "Alice"))
// Content Type をテスト
.andExpect(content().contentType("text/html;charset=UTF-8"))
// ページに指定したテキストが含まれるかテスト
.andExpect(content().string(containsString("Alice")));
}
}