본문 바로가기
Tips/Spring Boot

[Spring Boot] @DataJpaTest에서 JPAQueryFactory Bean 등록 안될때

by DevJaewoo 2022. 10. 27.
반응형

@DataJpaTest에서 JPAQueryFactory Bean 등록 안될때

@DataJpaTest@SpringBootTest와 달리 Entity와 SpringDataJpa 관련 Bean만 등록해주기 때문에, QueryDSL에서 사용하는 JPAQueryFactory Bean은 등록되지 않는다.

 

때문에 테스트를 실행하면 아래와 같이 JPAQueryFactory Bean을 찾을 수 없다는 에러가 뜬다.

Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
		...
	Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '$name$' defined in file [$file$]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.querydsl.jpa.impl.JPAQueryFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
		...
	Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.querydsl.jpa.impl.JPAQueryFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
		...

Bean이 등록되지 않아 발생한 문제이므로, 테스트 환경에서 Bean을 다시 등록해줌으로써 해결할 수 있다.

아래와 같이 JPAQueryFactory Bean을 등록해주는 @TestConfiguration 클래스를 만들고,

@TestConfiguration
public class TestConfig {

    @Bean
    public JPAQueryFactory jpaQueryFactory(EntityManager em) {
        return new JPAQueryFactory(em);
    }
}

 

이후 테스트를 수행하는 클래스에서 위의 클래스를 Import 시켜주면 된다.

@DataJpaTest
@Import(TestConfig.class)
class ClientRepositoryTest {

    @Autowired private ClientRepository clientRepository;

    @Test
    @DisplayName("ID")
    public void TestId() {
        //given
        Client client = Client.create("client", "email", "password");
        clientRepository.save(client);

        //when
        Client result = clientRepository.findById(client.getId()).orElse(null);

        //then
        assertThat(result).isNotNull();
        assertThat(result.getId()).isEqualTo(client.getId());
    }
}

 

테스트 결과


참고자료

반응형