• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

JPA Test Code 관련해서 질문이 있습니다.

24.02.24 02:12 작성 조회수 120

0

안녕하세요.

JPA와 Querydsl 학습을 위해서 테스트 코드를 작성 중에 궁금한 부분이 있어서 질문 드립니다.

 

조회를 위한 테스트 데이터를 save 하고, querydsl로 작성한 repository를 이용해서 데이터를 조회하여 검증하고 있습니다. 여기서 궁금한 부분은 테스트 데이터를 save 하고나서 EntityManger를 이용해서 영속성 컨텍스트를 비워주는 작업을 테스트 코드마다 해주는게 맞는지 궁금합니다.

 

영속성 컨텍스트를 비워주지 않고 조회하면 영속성 컨텍스트에 존재하는 데이터를 읽기 때문에 테스트가 깨집니다. 현업에서도 Repository 테스트 코드를 작성할 때, 테스트 데이터를 넣어준 후 매번 flush / clear를 해주는지 아니면 다른 Best Practice가 있는지 알고싶습니다.

 

class ProductQueryRepositoryTest extends DomainTestSupport {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductQueryRepository productQueryRepository;

    @Test
    @DisplayName("상품 아이디로 판매중인 상품 정보를 조회한다.")
    void findByIdIsSaleableTrue() throws Exception {
        // given
        ProductOption appleOption1 = createProductOption("1kg", 10000, 7000, 100, 10, true);
        ProductOption appleOption2 = createProductOption("2kg", 20000, 15000, 100, 5, false);
        Product apple = createProduct("사과", false, true, appleOption1, appleOption2);
        productRepository.save(apple);

        em.flush();
        em.clear();

        // when
        Optional<Product> optionalProduct = productQueryRepository.findByIdIsSaleableTrue(apple.getId());

        // then
        assertThat(optionalProduct).isPresent()
                .get()
                .extracting("name", "isSaleable", "isDeleted")
                .contains(apple.getName(), apple.getIsSaleable(), apple.getIsDeleted());

        List<ProductOption> productOptions = optionalProduct.get().getProductOptions();
        assertThat(productOptions).hasSize(1)
                .extracting("name", "originalPrice", "salesPrice", "stockQuantity", "maxOrderQuantity", "isSaleable", "isDeleted")
                .containsExactlyInAnyOrder(
                        tuple(appleOption1.getName(), appleOption1.getOriginalPrice(), appleOption1.getSalesPrice(), appleOption1.getStockQuantity(), appleOption1.getMaxOrderQuantity(), appleOption1.getIsSaleable(), appleOption1.getIsDeleted())
                );
    }

    // ... 중략

}

 

@RequiredArgsConstructor
@Repository
public class ProductQueryRepository {

    private final JPAQueryFactory queryFactory;

    public Optional<Product> findByIdIsSaleableTrue(Long id) {
        return Optional.ofNullable(
                queryFactory
                        .select(product)
                        .from(product)
                        .leftJoin(product.productOptions, productOption)
                        .fetchJoin()
                        .where(
                                product.id.eq(id),
                                product.isSaleable.isTrue(),
                                product.isDeleted.isFalse(),
                                productOption.isSaleable.isTrue(),
                                productOption.isDeleted.isFalse()
                        )
                        .fetchOne()
        );
    }

}

 

감사합니다.

답변 1

답변을 작성해보세요.

0

David님의 프로필

David

2024.02.24

안녕하세요. Anonymous님, 공식 서포터즈 David입니다.

네 생각하신대로 테스트를 실행하기 전, 후에 테스트 데이터의 처리(삽입, 제거)를 수행하도록 작성하게 됩니다.

감사합니다.

Anonymous님의 프로필

Anonymous

질문자

2024.02.28

감사합니다.