MockMvc 테스트 SpringMVC 컨트롤 러 사용 하기
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 에 대한 유닛 테스트 수 요 를 기본적으로 덮어 쓸 수 있 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Sorting Layer와 3D Object의 관계이것은 원래는 에 게재하고 있던 기사이지만, 뭐 자신의 블로그는 기술적인 기사를 도카도카 게재하는 장소도 아니기 때문에, 이쪽에도 병행해 게재해 둔다. 어느 날 질문을 받았다. "그러고 보니 unity에서 sorti...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.