MockMvc 테스트 SpringMVC 컨트롤 러 사용 하기

2165 단어 testspringMockMvc
MockMvc 는 springTest 가 제공 하 는 SpringMvc 에 대한 테스트 도구 입 니 다.이렇게 하면 단원 테스트 는 Dao 와 Service 층 에 대한 테스트 에 만 국한 되 지 않 게 할 수 있다.컨트롤 러 층 도 테스트 할 수 있다.풍부 한 단원 테스트 기능.테스트 할 때 servlet 용 기 를 자주 다시 시작 하지 않 고 테스트 작업 을 간소화 합 니 다.
MockMvc 는 사용자 의 요청 과 대응 을 모 의 하기 위해 ServletContext 가 필요 합 니 다.
우선, 테스트 클래스 의 머리 에 Annotation 을 추가 해 야 합 니 다.
@WebAppConfiguration
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration(locations = { "classpath:spring/applicationContext.xml" })

@ WebAppConfiguration 은 servletContext 를 도입 하 는 데 사 용 됩 니 다.
다음은 준 it 에서 테스트 클래스 를 작성 할 수 있 습 니 다.
demo 1 요청 헤더, 인자 없 는 get 요청 이 있 습 니 다.
샘플 코드 는 다음 과 같 습 니 다.
@Test
	public void    () throws Exception {
		ResultActions reaction=this.mockMvc.perform(MockMvcRequestBuilders.get("/service/test/testController")
				.accept(MediaType.APPLICATION_JSON)//     json
				.header("Timestamp", "1496656373783")
				.header("AppId", "1003"));
		reaction.andExpect(MockMvcResultMatchers.status().isOk());
		MvcResult mvcResult =reaction.andReturn();
		System.out.println(mvcResult.getResponse().getContentAsString());
	}

demo 2 요청 헤더, 요청 체 가 있 는 post 요청
샘플 코드 는 다음 과 같 습 니 다.
@Test
	public void    () throws Exception {
		PolicyInfoRequest request=new PolicyInfoRequest();
		request.setAnnualPremium(100);
		request.setPolicyNo("Test-222");
		request.setPolicyRebate(0.28f);
		request.setPolicyType(1);
		request.setRebateAmount(28f);
		String jsonRequest=JSON.toJSONString(request);
		ResultActions reaction =this.mockMvc.perform(MockMvcRequestBuilders.post("/policy/info/save")
				.contentType(MediaType.APPLICATION_JSON)//    json
				.header("Timestamp", "1496656373791")
				.header("AppId", "1003")
				.content(jsonRequest));
		reaction.andExpect(MockMvcResultMatchers.status().isOk());
		MvcResult mvcResult =reaction.andReturn();
		System.out.println(mvcResult.getResponse().getContentAsString());
	}

상기 두 가지 예 는 springtest 를 사용 하 는 MockMvc 가 Controller 에 대한 유닛 테스트 수 요 를 기본적으로 덮어 쓸 수 있 습 니 다.

좋은 웹페이지 즐겨찾기