쉬운 프로그래밍

[Spring Boot] ResponseEntity와 TestRestTemplate 본문

Programming/Spring Boot

[Spring Boot] ResponseEntity와 TestRestTemplate

쉬운형 2021. 2. 17. 16:29

REST API에 대한 기본적인 이해를 하고 있다고 가정한다.

 

1. ResponseEntity

스프링에서 제공하는 클래스 중에서 HttpEntity라는 클래스가 존재하는데 이는 Http 리퀘스트/리스폰스가 이루어질 때 Http 헤더와 바디를 포함하는 클래스이다.

 

RequestEntity와 ResponseEntity는 이 HttpEntity를 상속받는다.

 

즉 ResponseEntity는 사용자의 HttpRequest에 대한 응답하는 데이터를 가진다.  Http Status, Header, Body를 포함한다.

 

@RestController
public class HelloController {
	
    @GetMapping("/hello")
    public ResponseEntity hello() {
    	return new ResponseEntity(HttpStatus.OK);
    }
}

위와 같이 코드를 작성하고 /hello URL에 접근하면 Status값을 확인할 수 있다.

 

또한 위에서 설명했듯이 헤더와 바디(응답 데이터)를 ResponseEntity 객체에 담을 수 있다.

 

 

2. TestRestTemplate

TestRestTemplate은 REST 방식으로 개발한 API의 Test를 최적화 하기 위해 만들어진 클래스이다.

 

HTTP 요청 후 데이터를 응답 받을 수 있는 템플릿 객체이며 ResponseEntity와 함께 자주 사용된다.

 

Header와 Content-Type 등을 설정하여 API를 호출 할 수 있다.

 

TestRestTemplate에서 대표적으로 사용되는 것들을 살펴보면,

 

1. testRestTemplate.getForObject()

  - 기본 http 헤더를 사용하며 결과를 객체로 반환받는다.

 ProductDetailResponseDto item = this.testRestTemplate.getForObject(url, ProductDetailResponseDto.class);

  

2. testRestTemplate.getForEntity()

  - 마찬가지로 기본 http 헤더를 사용하며 결과를 ResponseEntity로 반환받는다.

ResponseEntity<Long> responseEntity = this.testRestTemplate.postForEntity(url, productRegisterRequestDto, Long.class);

 

3. testRestTemplate.exchange()

  - update할때 주로 사용된다. 결과를 ResponseEntity로 반환받는다. Http header를 변경할 수 있다.

// given
HttpEntity<ProductUpdateRequestDto> requestEntity = new HttpEntity<>(productUpdateRequestDto);

// when
ResponseEntity<Long> responseEntity = this.testRestTemplate.exchange(url, HttpMethod.PUT, requestEntity, Long.class);

 

 

아래 코드는 ResponseEntity와 TestRestTemplate을 활용한 테스트 코드 예제이다.

 

# 테스트 클래스

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @AfterEach
    public void tearDown() throws Exception {
        this.userRepository.deleteAll();
    }

    @Test
    public void 회원가입() throws Exception {
        // given
        UserRegisterDto userRegisterDto = UserRegisterDto.builder()
                .nickName("닉네임3")
                .email("asdf@naver.com")
                .password("123456")
                .address("대전광역시")
                .phone("010-0000-0000")
                .role(Role.GUEST)
                .build();

        String url = "http://localhost:" + this.port + "/login/doRegister";

        // when
        ResponseEntity<User> responseEntity = this.restTemplate.postForEntity(url, userRegisterDto, User.class);

        // then
        Assertions.assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
        Assertions.assertThat(responseEntity.getBody().getNickName()).isEqualTo(userRegisterDto.getNickName());

        List<User> all = this.userRepository.findAll();
        Assertions.assertThat(all.get(0).getNickName()).isEqualTo(userRegisterDto.getNickName());

    }



}

 

아래 코드는 호스트가 사용하지 않는 랜덤 포트를 테스트에 사용하겠다는 것을 의미한다.

webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT

 

# 컨트롤러

    @PostMapping("/login/doRegister")
    public User doRegisterUser(@RequestBody UserRegisterDto userRegisterDto) {
        return this.userService.registerUser(userRegisterDto);
    }

 

'Programming > Spring Boot' 카테고리의 다른 글

[Spring Boot] 인텔리제이 Live Reload 설정  (0) 2021.02.07
[Spring Boot] Spring Security Security Config  (0) 2021.02.02
[Lombok] @RequiredArgsConstructor  (0) 2021.02.01
[Spring Boot] OAuth 2.0 기본 세팅  (2) 2021.01.29
REST API  (0) 2021.01.26
Comments