@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void returnHello() throws Exception {
String hello = "hello";
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string(hello));
}
}
- @ExtendWith(SpringExtension.class)
- 테스트를 진행할 때 JUnit에 내장된 실행자 외에 다른 실행자를 실행
- SpringExtension이라는 스프링 실행자를 사용
- 스프링 부트 테스트와 JUnit 사이에 연결자 역할
- @WebMvcTest
- 여러 스프링 테스트 어노테이션 중, Web(Spring MVC)에 집중할 수 있는 어노테이션
- 선언할 경우 @Controller, @ContollerAdvice 등을 사용할 수 있음
- 단, @Service, @Component, @Repository 등은 사용할 수 없음
- 여기서는 컨트롤러만 사용하기 때문에 선언
- @Autowired
- 스프링이 관리하는 빈(Bean)을 주입
- private MockMvc mvc
- 웹 API 를 테스트할 때 사용
- 스프링 MVC 테스트의 시작점
- 이 클래스를 통해 HTTP GET, POST 등에 대한 API 테스트를 할 수 있음
- mvc.perform(get("/hello"))
- MockMvcRequestBuilders.get()
- MockMvc를 통해 /hello 주소로 HTTP GET 요청을 함
- 체이닝이 지원되어 아래와 같이 여러 검증 기능을 이어서 선언 가능
- .andExpect(status().isOK())
- MockMvcResultMatchers.status()
- mvc.perform의 결과를 검증
- HTTP Header의 Status를 검증
- 200,404,500 등의 상태를 검증
- Ok는 200 검증
- andExpect(content().string(hello))
- MockMvcResultMatchers.content()
- mvc.perform의 결과를 검증
- 응답 본문의 내용을 검증
- Controller에서 "hello"를 리턴하기 때문에 이 값이 맞는지 검증
public class HelloResponseDtoTest {
@Test
public void lombokTest(){
//given
String name = "test";
int amount = 1000;
//when
HelloResponseDto dto = new HelloResponseDto(name, amount);
//then
assertThat(dto.getName()).isEqualTo(name);
assertThat(dto.getAmount()).isEqualTo(amount);
}
}
- assertThat
- org.assertj.core.api.Assertions 의 테스트 검증 라이브러리의 검증 메소드
- 검증하고 싶은 대상을 메소드 인자로 받음
- 메소드 체이닝이 지원되어 isEqualTo와 같이 메소드를 이어서 사용할 수 있음
- isEqualTo
- assertj의 동등 비교 메소드
- assertThat에 있는 값과 isEqualTo의 값을 비교해서 같을 때만 성공
@Test
public void returnHelloDto() throws Exception {
String name = "hello";
int amount = 1000;
mvc.perform(
get("/hello/dto")
.param("name", name)
.param("amount", String.valueOf(amount))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.name",is(name)))
.andExpect(jsonPath("$.amount", is(amount)));
}
- param
- API 테스트할 때 사용될 요청 파라미터를 설정
- 단, 값은 String만 허용됨
- 그래서 숫자/날짜 등의 데이터도 등록할 때는 문자열로 변경해야만 가능
- jsonPath
- MockMvcResultMatchers.jsonPath()
- $를 기준으로 필드명을 명시
- 여기서는 name과 amount를 검증 $.name, $.amoun로 검증
- 참고자료
스프링 부트와 AWS로 혼자 구현하는 웹 서비스
'FrameWork > Spring' 카테고리의 다른 글
머스테치 (0) | 2021.08.21 |
---|---|
JPA Auditing으로 생성시간/수정시간 자동화하기 (0) | 2021.08.20 |
등록/수정/조회 API (0) | 2021.08.19 |
Spring Data JPA (0) | 2021.08.18 |
Spring Boot Annotations (0) | 2021.08.18 |