WebMvcTest 구현 중 아래와 같은 빈 인식을 못한다는 오류를 만났다.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jpaQueryFactory' defined in com.project.board.BoardApplication: Unsatisfied dependency expressed through method 'jpaQueryFactory' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManager' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
@WebMvcTest
class BoardControllerTest {
private final MockMvc mvc;
@MockBean
private BoardService boardService;
public BoardControllerTest(@Autowired MockMvc mvc) {
this.mvc = mvc;
}
@DisplayName("모든 게시판 조회 테스트 - 최신순")
@Test
void listTest() throws Exception {
// Given
PageRequest pageRequest = PageRequest.of(0, 5);
given(boardService.selectBoard(refEq(pageRequest))).willReturn(Page.empty());
// When & Then
mvc.perform(get("/v1/board/select"))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML_VALUE))
.andExpect(view().name("board/list"));
then(boardService).should().selectBoard(refEq(pageRequest));
}
}
@WebMvcTest
어노테이션은 MVC를 위한 테스트이다 Web Layer
만 로드한다. (ex:@Controller
, @RestController
, @ControllerAdvice
,@RestControllerAdvice
,@JsonComponent
,@Convert
,@GenericConverter
, Filter
,WebmvcConfigurer
,HandlerMethodArgumentResolver
등) 왜 JpaQueryFactory
가 빈 등록이 되지 않는다고 요류가 생기는지 이해가 되지 않았다. JpaQueryFactory
는 WebMVC
와 관련이 없기 때문이다.
구글링 결과 내가 JpaQueryFactor
를 빈으로 등록하기 위해 SpringApplication
에 작성한 코드 때문이였다. (@EnableJpaAuditing
도 문제)
@EnableJpaAuditing
@SpringBootApplication
public class BoardApplication {
public static void main(String[] args) {
SpringApplication.run(BoardApplication.class, args);
}
@Bean
public JPAQueryFactory jpaQueryFactory(EntityManager em){
return new JPAQueryFactory(em);
}
}
@WebMvcTest
어노테이션은 MVC 관련 빈만 등록되기 때문에 JPAQueryFactory
는 빈으로 등록이 안돼 오류가 발생했던 거였다.
그래서 나는 JPAQueryFactory
를 별도의 config 클래스를 만들어 빈 설정을 해줬다.
@EnableJpaAuditing
@Configuration
public class JpaConfig {
@PersistenceContext
private EntityManager em;
@Bean
public JPAQueryFactory jpaQueryFactory(){
return new JPAQueryFactory(em);
}
}
이렇게 해주고 실행하니 정상적으로 테스트를 통과했다. 가능한 SpringApplication
빈 설정을 하지 말고 config 클래스를 따로 만들어 빈을 관리하자