Spring

JUnit5 컨트롤러 통합 테스트

JJJAEOoni 2022. 6. 2. 12:10
반응형

왜 컨트롤러는 통합 테스트 하는 게 좋을까?

통합테스트 장점 : 분리해서 처리하지 않으니까 찝찝함이 줄어든다.

→ 프로젝트 전체 테스트 가능 (= 실제 테스트)

이것도 Mockito로 처리하면 가짜 테스트이다.
다 띄우는게 좋다.


MSA 도메인별로 서버 분리


MSA 설계 시 테스트할때
C를 때린 결과를 토대로 A 테스트를 할 때가 있는데,

이때 TestRestTemplate를 많이 사용한다.


모크로는 불가능하다.
모크는 자기 서버를 테스트 하는것이지 다른 서버는 테스트하지 못한다.

컨트롤러는 웬만하면 그냥 통합 테스트하자.

 

진짜 개큰회사에서는 WebMvcTest로 하지만 우린 그냥 통합 테스트하자.

포스트맨 사용할 필요없이 테스트 가능

근데 포스트맨 사용안할 수가 없어.
테스트 다 통과해도 눈으로 검증이 필요하다.

기존 서버가 8080으로 돌고있기 때문에
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
안쓰는 포트 잡아서 띄워준다.

 

// 통합테스트
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class BookApiControllerTest {

    @Autowired
    private TestRestTemplate rt; // 테스트 전용 RestTemplate

    @Autowired
    private BookRepository bookRepository;

    @Test
    public void bookSave_테스트() throws JsonProcessingException {

        BookSaveReqDto reqDto = new BookSaveReqDto();
        reqDto.setTitle("제목1");
        reqDto.setAuthor("메타코딩");

        // given (JSON 데이터)
        String body = new ObjectMapper().writeValueAsString(reqDto);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> request = new HttpEntity<>(body, headers);

        // when
        // json 응답받으니까 String으로 받음
        ResponseEntity<String> response = rt.exchange("/api/book", HttpMethod.POST, request, String.class);

        // then
        // DocumentContext는 json 분석 도구 (jayway 써드 파티 라이브러리)
        DocumentContext dc = JsonPath.parse(response.getBody());
        String author = dc.read("$.author");
        assertEquals(201, response.getStatusCodeValue());
        assertEquals("메타코딩", author);
    }

    @Test
    public void bookFindOne_테스트() throws JsonProcessingException {

        // given (JSON 데이터)
        bookRepository.save(new Book(1L, "제목1", "메타코딩"));

        Long id = 1L;

        // when
        // json 응답받으니까 String으로 받음
        ResponseEntity<String> response = rt.exchange("/api/book/" + id, HttpMethod.GET, null, String.class);

        // then
        // DocumentContext는 json 분석 도구 (jayway 써드 파티 라이브러리)
        DocumentContext dc = JsonPath.parse(response.getBody());
        String author = dc.read("$.author");
        assertEquals(200, response.getStatusCodeValue());
        assertEquals("메타코딩", author);
    }
}

 

서비스 : mock : resultAction

컨트롤러 : testTemplate : DocumentContext
               : mockmvc      : resultAction

 

 

 

[출처]

 

https://cafe.naver.com/metacoding

 

메타코딩 : 네이버 카페

코린이들의 궁금증

cafe.naver.com

메타 코딩 유튜브

https://www.youtube.com/c/%EB%A9%94%ED%83%80%EC%BD%94%EB%94%A9

 

메타코딩

문의사항 : getinthere@naver.com 인스타그램 : https://www.instagram.com/meta4pm 깃헙 : https://github.com/codingspecialist 유료강좌 : https://www.easyupclass.com

www.youtube.com

 
반응형