킹의 개발일지

JUnit, Mockito 및 MockMvc를 사용한 스프링 부트 단위 테스트(3) 본문

Junit

JUnit, Mockito 및 MockMvc를 사용한 스프링 부트 단위 테스트(3)

k1ng 2022. 6. 16. 01:58

Springboot unit testing support

스프링 부트가 제공하는 테스트 지원 특징

스프링부트가 제공하는 테스트 지원을 받으려면 먼저 스프링 부트 프로젝트에 spring-boot-starter-test 종속성을 추가해주어야한다.

 

해당 종속성은 JUnit 5에 대한 transtive 종속성을 포함하고 있기 때문에 여타 필요한 종속을 명시적으로 나열할 필요 없어진다.

 

테스트시에만 사용할 것이기 때문에 scope를 테스트로 해준다.

 

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

 

다음으로 특징으로, 스프링부트가 제공하는 @SpringBootTest 어노테이션은 한 줄로 많은 기능을 사용할 수 있게 해준다.

 

  • Application context를 로드할 수 있게 해준다. 때문에 @Autowired 어노테이션을 써서 Application context을 로드해 원하는 빈을 직접 꺼내어 사용할수도 있다.
  • 때문에 테스트에서도 스프링 DI를 사용할 수 있다.

 

@Autowired
CollegeStudent student;

@Autowired
StudentGrades studentGrades;

@Autowired
ApplicationContext applicationContext;


@DisplayName("Create student without grade init")
@Test
public void createStudentWithoutGradeInit() {
    CollegeStudent studentTwo = applicationContext.getBean("collegeStudent", CollegeStudent.class);
    studentTwo.setFirstname("Juhong");
    studentTwo.setLastname("An");
    studentTwo.setEmailAddress("test@test.com");

    assertNotNull(studentTwo.getFirstname());
    assertNotNull(studentTwo.getLastname());
    assertNotNull(studentTwo.getEmailAddress());
    assertNull(studentGrades.checkNull(studentTwo.getStudentGrades()));
}
  • 그리고 @Value 어노테이션으로 특정 properties 파일에 있는 데이터를 사용할 수 있다.

 

@Value("${info.app.name}")
private String appInfo;

@Value("${info.school.name}")
private String schoolName;

@Value("${info.app.description}")
private String appDescription;

@Value("${info.app.version}")
private String appVersion;

 

그리고 main 패키지와 동일하게 test 패키지를 구성해준다면

 

다른 추가 구성이 필요없이 자동으로 스캔해서 의존을 주입할 수 있게 해준다.

 

만약 main 패키지 구조와 다르게 하고 싶다면, @SpringBootTest(class=…Application.class) 처럼 어노테이션의 속성으로 @SpringBootApplication 어노테이션이 있는 클래스의 위치를 명시해주야한다.

 

 

main 패키지와 동일한 패키지 구조

 

그러나 이런 편리한 이점 외에도 @SpringBootTest 어노테이션을 사용했을 때 단점또한 있다.

 

  • 실제 구동되는 애플리케이션의 설정과 모든 Bean을 로드하기 때문에 시간이 오래걸리고 무겁다.
  • 테스트 단위가 크기 때문에 디버깅이 어려운 편이다.
  • 외부 API 콜같은 Rollback 처리가 안되는 테스트 진행을 하기 어렵다.

때문에 테스트를 원하는 관심 분야만 테스트 할 수 있도록 스프링은 슬라이스 테스트 어노테이션들을 제공한다.

 

이와 관한 공부는 추후 포스팅할 예정이다.