Unit Test Controllers with Spring MVC Testby Pigbrain
스프링 MVC Test 프로젝트는 컨트롤러를 테스트 할 수 있는 기능을 제공한다
Getting Ready
Application Setup
pom.xml에 디펜던시를 추가한다
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>3.2.3.RELEASE</version></dependency><!-- This is for mocking the service --><dependency><groupId>org.mockito</groupId><artifactId>mockito-all</artifactId><version>1.9.5</version><scope>test</scope></dependency><!-- Optional --><dependency><groupId>org.hamcrest</groupId><artifactId>hamcrest-core</artifactId><version>1.3</version><scope>test</scope></dependency><dependency><groupId>org.hamcrest</groupId><artifactId>hamcrest-library</artifactId><version>1.3</version><scope>test</scope></dependency>
publicclassIndexControllerTest{@MockprivateSampleServicesampleService;@InjectMocksprivateIndexControllerindexController;privateMockMvcmockMvc;@Beforepublicvoidsetup(){// Process mock annotationsMockitoAnnotations.initMocks(this);// Setup Spring test in standalone modethis.mockMvc=MockMvcBuilders.standaloneSetup(indexController).build();}@TestpublicvoidtestCreateSignupFormInvalidUser()throwsException{when(sampleService.saveFrom(any(SignupForm.class))).thenThrow(newInvalidUserException("For Testing"));this.mockMvc.perform(post("/create").param("email","mvcemail@test.com").param("firstName","mvcfirst").param("lastName","mvclastname")).andExpect(status().isOk()).andExpect(forwardedUrl(IndexController.PAGE_INDEX)).andExpect(model().attributeExists("page_error"));}}