@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = HelloController.class)
class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void hello가_리턴된다() throws Exception{
String hello = "hello";
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string(hello));
}
}
@ExtendWith
@WebMvcTest
- 여러 스프링 테스트 어노테이션 중 Web(Spring Mvc)에 집중할 수 있는 어노테이션
- 선언할 경우 Controller, ControllerAdvice 등을 사용할 수 있지만 Service, Repository, Component등은 선언 할 수 없음.
@Autowired
- 스프링이 관리하는 bean을 주입 받음.
@private MockMvc mvc
- 웹 API를 테스트할 때 사용.
- 스프링 MVC테스트의 시작점.
- 이 클래스를 통해 GET, POST 등에 대한 API 테스트를 할 수 있음.
mvc.perform(get("/hello"))
- MockMvc를 통해 /hello 주소로 HTTP GET요청을 함.
.andExpected(status().isOk())
- mvc.perform의 결과 검증
- HTTP Header의 status를 검증(200, 404 ,500)
- 여기서는 200인지 아닌지를 검증.
.andExpected(content().string(hello))
- 응답 본문의 내용을 검증.
- 여기서는 Controller에서 hello를 리턴하기에 이것이 맞는지 검증.
HelloController 코드를 롬복으로 전환하기
@Getter
@RequiredArgsConstructor
public class HelloResponseDto {
private final String name;
private final int amount;
}
@Getter
- 자동으로 getter 생성
@RequiredArgsConstructor
- 선언된 모든 final 이 붙어있는것의 생성자를 생성해준다.
- final 없으면 X
class HelloResponseDtoTest {
@Test
public void 롬복_기능_테스트(){
//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);
}
}
롬복 기능 테스트 성공적.
@RestController//JSOM반환하는 컨트롤러로 만들어줌. @Responsebody를 각 메소드마다 선언했던것을 한번에 사용할수있게 해준다생각.
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello";
}
@GetMapping("/hello/dto")
public HelloResponseDto helloDto(@RequestParam("name") String name, @RequestParam("amount") int amount){
return new HelloResponseDto(name, amount);
}
}
HelloController에 롬복 기능 추가.
@RequestParam
- 외부에서 API로 넘긴 파라미터를 가져오는 어노테이션.
- 여기에서는 name(RequestParam("name"))이란 이름으로 넘긴 파라미터를 메소드 파라미터 name(String name)에 저장하게 됩니다.
@Test
public void HelloDto가_리턴된다() throws Exception{
//given
String name = "taesoon";
int amount = 1000;
//when
mvc.perform(
get("/hello/dto")
.param("name", name)
.param("amount",String.
valueOf(amount)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is(name)));
}
HelloController에 추가한 기능 테스트.
param
api테스트 할때 사용될 요청 파라미터를 설정.
단 String만 허용
따라서 문자열로 변경해야만 가능.
jsonPath
JSON 응답값을 필드별로 검증할 수 있는 메서드
$를 기준으로 필드명을 명시
'Spring > 스프링부트와 AWS로 혼자구현하는 웹 서비스' 카테고리의 다른 글
섹션7. AWS RDS (1) | 2023.02.05 |
---|---|
섹션 6. AWS 서버 환경을 만들어보자 - AWS EC2 (0) | 2023.01.30 |
5장. 스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현하기 (0) | 2023.01.29 |
4장. 머스테치로 화면 구성하기 (0) | 2023.01.25 |
3장. 스프링 부트에서 JPA로 DB를 다뤄보자 (0) | 2023.01.24 |