프로그래밍 노트/SPRING BOOT

[Spring Boot] 스프링부트 테스트하기

깡냉쓰 2019. 9. 16. 23:06
728x90
반응형

단위/통합 테스트 전용 스타터 폼 spring-boot-starter-test 만 있으면 손쉽게 테스트가 가능하다.
(Junit, Hamcrest, Mockito 등이 존재)

pom.xml 추가

<dependency>
      <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

spring-test, junit, hamcrest, objenesis, mockito JAR 파일 의존성

스프링 부트 테스트 기본

기본 스프링 데이터 테스트 코드

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ToyApplicationTests {

    @Test
    public void contextLoads() {
    }

}

@RunWith(SpringJunit4ClassRunner.class)

  • Junit 라이브러리의 @RunWith는 제이유닛 내장 실행기(runner) 대신 SpringJunit4ClassRunner.class 클래스를 참조하여 테스트를 실행. Junit의 BlockJunit4ClassRunner를 커스터마이징한 클래스로, 스프링 테스트 컨택스트 프레임워크의 모든 기능을 제공

SpringRunner

  • SpringJunit4ClassRunner를 상속한 클래스로, 사실상 클래스 이름만 짧게 줄인 동일한 클래스

@SpringBootTest

  • 일반적인 스프링 부트 기반의 테스트 클래스에 붙이는 어노테이션. 속성을 추가해서 애플리케이션에 따라 설정을 다르게 할 수 있음

스프링 부트 웹 테스트

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ToyApplicationTests {

    @Test
    public void contextLoads() {
    }

}

@WebAppConfiguration은 org.springframework.web.context.WebApplicationContext 구현체를 불러오는 클래스 레벨 애너테이션으로, 웹 애플리케이션과 관련된 파일이나 빈은 모두 접근할 수 있게됨

실습

간단히 테스트할 웹 어플리케이션을 만들어보자!! User.java

@Getter
@Setter
@AllArgsConstructor
public class User {
    private String name;
    private String age;
    private String created;
}

UserController.java

@RestController
public class UserController {
    private static List<User> entityList = new ArrayList<>();
    static{
        entityList.add(new User("어린깡냉", "20", "01/01/2019"));
        entityList.add(new User("KANG", "30", "01/01/2020"));
        entityList.add(new User("나이많은 깡냉", "40", "01/01/2021"));
    }

    @GetMapping("/users")
    public List<User> getAll(){
        return entityList;
    }

    @GetMapping("/users/{name}")
    public List<User> getUserByName(@PathVariable String name){
        return entityList.stream()
                .filter(user -> user.getName().toLowerCase().contains(name.toLowerCase()))
                .collect(Collectors.toList());
    }

    @PostMapping("/users")
    public User add(@RequestBody User user){
        entityList.add(user);
        return user;
    }
}

JSON 객체 테스트에 유용한 유틸리티 중 Jayway(제이웨이)에서 나온 JsonPath라는 라이브러리가 있다.
아직 익숙치 않지만, 이 것을 사용해서 테스트해보자.

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <scope>test</scope>
</dependency>

Test 코드

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class) // MockMvc가 만들어져서 사용할 수 있음
public class UserControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void getAll() throws Exception {
        mockMvc.perform(get("/users"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$", iterableWithSize(3)))
                .andExpect(jsonPath("$[0]['name']", is(equalTo("어린깡냉"))));
    }

    @Test
    public void findByName() throws Exception {
        mockMvc.perform(get("/users/KANG"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$", iterableWithSize(1)))
                .andExpect(jsonPath("$[0]['name']", is(equalTo("KANG"))));
    }
}
728x90
반응형