BackEnd/Spring Boot

JPA 테스트 환경 구축

Raconer 2023. 6. 10. 15:32
728x90

테스트 환경 구축

JPA를 사용하더라도 Controller, Service를 테스트를 해야 하고
이를 위해 테스트 환경을 구축 하였고 이를 정리한 내용입니다.

테스트 구축 순서

테스트 구축시 환경

  1. 프로젝트 구조

    src
    └───test
       ├───java
       │   └───com
       │       └───jpa
       │           └───test
       │               └───service
       │                       ServiceTest.java
       │
       └───resources
               application-test.yml
  2. Dependency

  dependencies {
      implementation 'org.springframework.boot:spring-boot-starter-web'
      implementation 'org.springframework.boot:spring-boot-starter'
      implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
      runtimeOnly 'com.mysql:mysql-connector-j'

      compileOnly 'org.projectlombok:lombok'
      annotationProcessor 'org.projectlombok:lombok'
      developmentOnly 'org.springframework.boot:spring-boot-devtools'
      testImplementation 'org.springframework.boot:spring-boot-starter-test'
  }

ServiceTest.java

Service테스트 할때 주석을 제거 한후 적용 하시면 됩니다.


import com.jpa.commerce.entity.category.CategoryEntity;
import com.jpa.commerce.repository.category.CategoryRepository;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
// import org.springframework.context.annotation.Import;

import java.util.List;

  @DisplayName("Service Test")
  @DataJpaTest // JPA 테스트 하기 위해 생성 하며 기본적으로 rollback 된다.
  @ActiveProfiles("test") // active 가 test
  // @Import(TestService.class) // Service 테스트를 할때 
  @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // H2와 같은 DB를 사용하는게 아니라 현재 사용하고 있는 DB 에 적용된다.
  public class CategoryServiceTest {

      @Autowired
      private TestRepository testRepository;

      // @Autowired
      // private TestService testService; //Service 테스트 할때 

      @Test
      public void getListTest(){
          List<TestEntity> testList = this.testRepository.findAll();
          System.out.println(testList.toString());
      }

  }
728x90

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

JPA Entity여러 경우 적용_1  (0) 2023.06.11
JPA @Column 옵션  (0) 2023.06.10
JPA GenerationType 속성  (0) 2023.06.09
JPA의 ddl-auto 속성과 그 특징  (0) 2023.06.09
JPA 적응기_1  (0) 2023.05.21