@WebAppConfiguration 애너테이션은 SpringJUnit4ClassRunner가 애플리케이션 컨텍스트로 (기본값인 비웹용 ApplicationContext가 아니라) WebApplicationContext를 생성하도록 선언한다.
setupMockMvc() 메서드는 JUnit의 @Before 애너테이션을 붙여 다른 테스트 메서드보다 먼저 실행해야 함을 나타낸다. 이 메서드는 주입된 WebApplicationContext를 webAppContextSetup() 메서드에 전달한 후 build() 메서드를 호출하여 MockMvc 인스턴스를 생성하고, 테스트 메서드에서 사용할 인스턴스 변수에 할당한다.
MockMvc를 생성했으니 이제 몇 가지 테스트 메서드를 작성할 수 있다. 먼저 간단한 /로 HTTP GET 요청을 수행하고 기대한 모델과 뷰를 반환하는지 검증하자. 다음 homePage() 테스트 메서드로 이 검증을 수행한다.
package readinglist; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; … import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; … public class MockMvcWebTests { … @Test public void homePage() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get(”/”)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name(“readingList”)) .andExpect(MockMvcResultMatchers.model().attributeExists(“books”)) .andExpect(MockMvcResultMatchers.model().attribute(“books”, Matchers.is(Matchers.empty()))); } }