반응형
@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());
}
}
참고자료
반응형
'Tips > Spring Boot' 카테고리의 다른 글
[Spring Boot] WebSecurityConfigurerAdapter Deprecated 해결하기 (0) | 2022.11.15 |
---|---|
[Spring Boot] Process 'Gradle Test Executor 1' finished with non-zero exit value 1 해결법 (0) | 2022.10.30 |
[Spring Boot] OSIV (Open Session In View) 비활성화 후 JPA 조회 안될 때 (0) | 2022.09.21 |
[Spring] 빌드 시 invalid source release: XX 뜰 때 (0) | 2022.08.31 |
[Spring Boot] Infinite recursion (StackOverflowError) 오류 날 때 (0) | 2022.02.23 |