본문으로 바로가기
728x90

 

Chapter02

스프링부트에서 테스트 코드를 작성하자

 

 

테스트 코드의 장점

 

- 매번 코드를 수정할 때마다 톰캣을 내렸다가 다시 실행하는 일을 반복을 없애줌

- System.out.println()과 같은 눈으로 검증해야 하는 번거로움없이 자동검증

- 개발자가 만든 기능을 안전하게 보호

(ex. 새로운 B라는 기능이 추가됬을 때 이 기능만을 검증하여 기존에 잘되던 A라는 기능에 추가 가능)

 

 

* 테스트 코드 작성하기

 

Java 디렉토리에서 New -> Package

 

com.qwon.springboot 패키지 & Application 클래스에 아래와 같이 작성

 

 

그 아래 web패키지를 만들고 HelloController 클래스 생성

 

이제 테스트 코드를 검증하기 위해 src/test/java 디렉토리에 앞에서 생성했던 패키지를 그대로 다시 생성한다.

 

테스트 클래스는 기존의 클래스에서 뒤에 Test를 붙여 생성한다.

 

 

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
package com.qwon.springboot.web;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class)
public 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));
    }
}
 
 

 

 

이후, Run hello가_리턴된다()를 실행 -> 테스트 통과

 

 

Application.java 파일로 이동해 마찬가지로 main 메소드의 왼쪽 화살표 클릭

 

Run 'Application.main()' 실행

 

 

실행해보면 톰캣서버가 8080 포트로 실행되었다는 로그가 출력

 

웹 브라우저를 열어 localhost:8080/hello로 접속하면 아래와 같이 hello문자열이 출력

 

 

* 롬복 소개 및 설치

 

롬복의 역할 : 자바를 개발할 때 자주 사용하는 코드 Getter, Setter,

기본생성자, toString 등을 어노테이션으로 자동 생성

 

 

먼저, build.gradle에 compile('org.projectlombok:lombok') 코드 추가 -> Refresh

 

 

 

다음으로, ctrl+shift+a를 눌러 plugins 검색 -> lombok 설치

 

 

기존 코드를 롬복으로 변경하기 -> 테스트 코드를 통해 잘 변경되는지 확인

 

src/main의 web 패키지에 dto 패키지 추가 -> HelloResponseDto 생성

 

 

src/test의 web패키지에 dto 패키지 추가 -> HelloResponseDtoTest

 

 

HelloResponseDtoTest.java를 실행할 때

 

error: variable name not initialized in the default constructor
private final String name;
^

error: variable name not initialized in the default constructor
private final String amount;
^

 

위와 같은 오류가 발생하였는데 이는 gradle 5부터는 어노테이션을 구별해서 추가해줘야 한다고 하여

 

alt+F12를 눌러 터미널 창에서

gradlew wrapper --gradle-version 4.10.2

위와 같은 코드를 삽입하여 해결하였다.

 

이제, HelloController로 돌아가 새로 만든 ResponseDto를 사용하도록 코드 추가

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.qwon.springboot.web;
 
import com.qwon.springboot.web.dto.HelloResponseDto;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
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);
    }
}
 
 
 

 

name과 amount가 추가된 API를 테스트하는 코드를 HelloControllerTest에 추가

 

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.qwon.springboot.web;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
 
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class)
public 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));
    }
 
    @Test
    public void helloDto가_리턴된다() 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)));
    }
}
 
 

 

마지막으로 추가된 API를 테스트 해보기

 

 

json이 리턴되는 API 역시 정상적으로 테스트가 통과하는 것을 확인할 수 있다.

 

 

728x90