[SPRING]통합테스트

라미·2024년 3월 4일

spring

목록 보기
17/17
post-thumbnail

통합테스트

단위테스트 vs 통합 테스트

단위테스트(Unit Test)
하나의 모듈이나 클래스에 대해 세밀한 부분까지 테스트가 가능
모듈간의 상호 작용 검증은 할 수 없다.

통합 테스트(Integration Test)
두 개 이상의 모듈이 연결된 상태를 테스트 할 수 있다.
모듈 간의 연결에서 발생하는 에러 검증이 가능하다.


Spring Boot를 이용한 통합 테스트

  • 통합 테스트
    • 여러 단위 테스트를 하나의 통합된 테스트로 수행합니다.
    • 단위 테스트 시 Spring은 동작되지 않습니다.
  • "@SpringBootTest"
    • 스프링이 동작되도록 해주는 애너테이션입니다.
    • 테스트 수행 시 스프링이 동작합니다.
      • Spring IoC/DI 기능을 사용 가능합니다.
      • Repository를 사용해 DB CRUD가 가능합니다.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // 서버의 PORT 를 랜덤으로 설정합니다.
@TestInstance(TestInstance.Lifecycle.PER_CLASS) // 테스트 인스턴스의 생성 단위를 클래스로 변경합니다.
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) // 테스트 순서 정해주는 annotation
class ProductServiceIntegrationTest {

    @Autowired
    ProductService productService; // 테스트할 객체 주입받기
    @Autowired
    UserRepository userRepository; // 테스트할 객체 주입받기
    
    // 공유해서 사용할 필드
    User user;
    ProductResponseDto createdProduct = null;
    int updatedMyPrice = -1;

    @Test
    @Order(1)
    @DisplayName("신규 관심상품 등록")
    void test1() {
        // given : 테스트 할 데이터 세팅
        String title = "Apple <b>에어팟</b> 2세대 유선충전 모델 (MV7N2KH/A)";
        String imageUrl = "https://shopping-phinf.pstatic.net/main_1862208/18622086330.20200831140839.jpg";
        String linkUrl = "https://search.shopping.naver.com/gate.nhn?id=18622086330";
        int lPrice = 173900;
        ProductRequestDto requestDto = new ProductRequestDto(
                title,
                imageUrl,
                linkUrl,
                lPrice
        );
        // 신규상품 등록에 필요한 user 가져온다
        user = userRepository.findById(1L).orElse(null);

        // when : 테스트 실행
        ProductResponseDto product = productService.createProduct(requestDto, user);

        // then
        assertNotNull(product.getId());
        assertEquals(title, product.getTitle());
        assertEquals(imageUrl, product.getImage());
        assertEquals(linkUrl, product.getLink());
        assertEquals(lPrice, product.getLprice());
        assertEquals(0, product.getMyprice());
        createdProduct = product; // 제대로 생성이 됐다면 createdProduct 에 생성된 createdPrduct를 넣어준다
    }

    @Test
    @Order(2)
    @DisplayName("신규 등록된 관심상품의 희망 최저가 변경")
    void test2() {
        // given
        Long productId = this.createdProduct.getId();
        int myPrice = 173000;
        ProductMypriceRequestDto requestDto = new ProductMypriceRequestDto();
        requestDto.setMyprice(myPrice);

        // when
        ProductResponseDto product = productService.updateProduct(productId, requestDto);

        // then
        assertNotNull(product.getId());
        assertEquals(this.createdProduct.getTitle(), product.getTitle());
        assertEquals(this.createdProduct.getImage(), product.getImage());
        assertEquals(this.createdProduct.getLink(), product.getLink());
        assertEquals(this.createdProduct.getLprice(), product.getLprice());
        assertEquals(myPrice, product.getMyprice());
        this.updatedMyPrice = myPrice;
    }

    @Test
    @Order(3)
    @DisplayName("회원이 등록한 모든 관심상품 조회")
    void test3() {
        // given
        // when
        Page<ProductResponseDto> productList = productService.getProducts(user,
                0, 10, "id", false);

        // then
        // 1. 전체 상품에서 테스트에 의해 생성된 상품 찾아오기 (상품의 id 로 찾음)
        Long createdProductId = this.createdProduct.getId();
        ProductResponseDto foundProduct = productList.stream()
                .filter(product -> product.getId().equals(createdProductId))
                .findFirst()
                .orElse(null);

        // 2. Order(1) 테스트에 의해 생성된 상품과 일치하는지 검증
        assertNotNull(foundProduct);
        assertEquals(this.createdProduct.getId(), foundProduct.getId());
        assertEquals(this.createdProduct.getTitle(), foundProduct.getTitle());
        assertEquals(this.createdProduct.getImage(), foundProduct.getImage());
        assertEquals(this.createdProduct.getLink(), foundProduct.getLink());
        assertEquals(this.createdProduct.getLprice(), foundProduct.getLprice());

        // 3. Order(2) 테스트에 의해 myPrice 가격이 정상적으로 업데이트되었는지 검증
        assertEquals(this.updatedMyPrice, foundProduct.getMyprice());
    }
}

흠....아직 잘 모르겠다 통합테스트..

0개의 댓글