inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

실전! Querydsl

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

226

Anonymous

작성한 질문수 9

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()
        );
    }

}

 

감사합니다.

java jpa

답변 1

0

David

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

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

감사합니다.

0

Anonymous

감사합니다.

SpringBoot 4.X에서의 Querydsl 설정

0

88

2

querydsl 오픈소스에 대한 질문

0

72

1

예제에서의 카운트 쿼리에서 join문과 where문은 필요없지 않나요?

0

109

1

Querydsl 6.X버전에 대해서 어떻게 생각하시나요?

0

317

2

여러 테이블 조인하여 통계치를 구하고자 할 때 어떤 방법이 더 효율적일까요

1

70

1

fetchResults()는 더이상 권장되지 않는다는데 맞나요?

0

160

1

querydsl sum() 메서드 없어요.

0

159

2

build 디렉터리 생성

0

136

2

자바 ORM 표준 JPA 프로그래밍 - 기본편 듣고 바로 학습해도 괜찮을까요?

0

114

2

현재 Querydsl에서 from절 서브쿼리를 지원하나요?

0

91

1

오타 제보 드립니다.

0

72

2

벌크 연산과 flush, clear

0

76

1

Run As Intellij 로 변경시 Q타입 import 불가

0

88

1

QHello import하기 문제 발생

0

147

2

등록된 함수 보는법(H2Dialect) 질문

0

68

2

5.0부터 Querydsl은 향후 fetchCount() , fetchResult() 를 지원하지 않기로 결정했다고 하는데 이에 맞는 강의

1

196

2

[환경설정 PDF 부트 3.0이후 설명 질문] build.gradle에 compileQuerydsl을 정의하지 않은 상태에서 Gradle->Tasks->other->compileQuerydsl을 클릭하라고 하는 이유가 무엇인가요??

1

200

1

querydsl 설정 문제

0

222

2

quey dsl 설정부분

0

158

2

count 쿼리 관련 질문입니다!

0

75

1

stringtemplate를 이용하여 where절 검색 방법 질문 드립니다.

0

89

1

답변부탁드리겠습니다.

0

89

2

(OrderSpecifier)관련 내용 어디있을가요

0

65

1

중급문법 벌크연산에서

0

81

2