Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- awscli
- 도메인
- filterexpression
- MockMvc
- 오류
- secondaryindex
- DynamoDB
- IdClass
- AWS
- testresttemplate
- 스프링
- compositekey
- EmbeddedId
- Java
- 다이나모디비
- 테스트코드
- 로드밸런서
- awscloud
- query
- annotation
- Springsecurity
- 자바
- 스프링테스트
- javaspring
- Route53
- markerinterface
- Spring
- 자바스프링
- partiql
- 개발
Archives
- Today
- Total
아장아장 개발 일기
Spring MockMvc 사용법 본문
MockMvc 테스트 기본 소스
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.MOCK)
@RunWith(SpringRunner.class)
@ActiveProfiles("dev")
public class TestControllerTest extends TestCase {
@Autowired
private MockMvc mockMvc;
- @AutoConfigurationMockMvc : mockMvc 의존성 주입을 위한 어노테이션이며, 해당 어노테이션이 없으면 MockMvc가 자동 의존성 주입되지 않고 nullPointException 발생.
- @ActiveProfiles(”dev”) : 프로젝트에 application.properties 등을 통해 여러 개의 프로필이 설정되어있을 경우 이 어노테이션을 사용해 어떤 프로필로 테스트 할 것인지 명시. 실서버와 개발서버 등 실행 환경이 나뉘어진 프로젝트의 경우, 이를 설정하지 않으면 의도하지 않은 db에 데이터 조작이 일어날 수 있으니 표시 필수.
mockMvc 테스트 코드는 크게 두 부분으로 나뉩니다.
- 어떤 요청을 보낼 것인지(MockHttpServletRequestBuilder)
- 해당 요청을 보낸 후 결과(MvcResult) 및 평가
MockMVC 테스트 코드 예시
@Test
@WithUserDetails(value="wsh@test.com") // 실제 유저정보를 사용해 테스트 진행
public void 테스트등록_비활성화() throws Exception {
Test test = new Test();
test.setImageUrl("");
test.setTitle("테스트 전용 데이터");
test.setIntroduction("테스트");
test.setMain(false);
test.setVisible(false);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestJson =ow.writeValueAsString(test);
// 1. 어떤 요청을 보낼 것인지 구체화
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/updateEachProduct")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(requestJson)
.with(csrf());
// 2. 해당 요청에 대한 결과
MvcResult result = mockMvc.perform(builder).andExpect(jsonPath("$.data.seq").value(0)).andReturn();
MockHttpServletResponse response = result.getResponse();
String contentAsString = response.getContentAsString();
System.out.println("contentAsString = " + contentAsString);
}
위는 @ModelAttribute으로 데이터를 받아 상품 정보를 저장하는 컨트롤러를 테스트하는 소스입니다. 데이터를 @ModelAttribute으로 받는지, @RequestParam, @RequestBody 등으로 받는지에 따라 builder를 작성하는 방식이 달라집니다.
요청에 대한 결과에 대한 평가는 ‘andExpect()’을 통해 하는데, ‘status().isOk()’나 아래의 소스처럼 return 받은 json형식의 body의 요소가 기대와 일치하는지 등을 평가할 수도 있습니다.
'개발 > Spring' 카테고리의 다른 글
Jar 파일 PathNotFound 오류 해결 방법 (0) | 2022.10.21 |
---|---|
@Component VS @Service VS @Repository 어노테이션 차이 (0) | 2022.08.18 |
Spring Security ‘hasAnyAuthority()’ VS ‘hasAnyRole()’ (0) | 2022.04.21 |
Spring MockMvc와 TestRestTemplate 비교 (0) | 2022.04.19 |
Lombok Builder로 초기값 세팅하기 (0) | 2022.04.01 |
Comments