Blog

[Spring-LDW] 스프링 시큐리티 추가 후 @WebMvcTest에서 OAuthService를 못찾는 오류 해결

Category
Author
citeFred
citeFred
PinOnMain
1 more property
스프링 부트와 AWS로 혼자 구현하는 웹 서비스  : 인텔리제이, JPA, JUnit 테스트, 그레이들, 소셜 로그인, AWS 인프라로 무중단 배포까지 이동욱 저
Table of Content

이전 테스트코드와 다른점

[Spring-LDW] 테스트코드 수정 중 오류해결 could not prepare statement; SQL … 위 게시글과 비슷하게 CustomOAuth2UserService를 못찾는 문제가 발생하고 있다. 하지만 차이점은 @SpringBootTest인 위 테스트 코드로 해당 부트 어플리케이션 전체를 스캔함과 다르게 해당 코드는 @WebMvcTest 로 Controller 계층만을 위한 테스트로 정의되었기 때문이다. 따라서 CustomOAuth2UserService 를 스캔하지 못한다.

스캔 대상에서 SecurityConfig를 제거

@WebMvcTest어노테이션에 excludeFilters 속성을 추가하여 SecurityConfig.class를 제거한다. 해당 방법은 추후 사용하지 않는 것을 권장하고 있다.
@ExtendWith(SpringExtension.class) @WebMvcTest(controllers = HelloController.class, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class) } ) public class HelloControllerTest { @Autowired private MockMvc mvc; ...
Java
복사

모의 인증 사용자 추가 @WithMockUser

@WithMockUser어노테이션을 통해 가짜 인증 사용자를 생성하여 추가해준다.
@Test @WithMockUser(roles = "USER") public void hello() throws Exception { String hello = "hello"; ... @Test @WithMockUser(roles = "USER") public void helloDto가_리턴() throws Exception{ String name = "hello"; int amount = 1000; ...
Java
복사
이후 테스트 실행 시 다음과 같은 오류로 변경된다.

JPA metamodel must not be empty! 오류

위 오류는 @EnableJpaAuditing으로 인해 발생하는 오류이다. 이를 위해서는 최소 1개의 @Entity 클래스가 필요한데 @WebMvcTest다 보니 스캔 할 수 없기 때문에 문제가 생기게 된다. 따라서 메인 클래스인 LdwSpringApplication.java에서 JpaAuditing 어노테이션을 제거하고 별도로 config로 분리하여 관리하도록 한다.

LdwSpringApplication.java

package com.citefred.ldwspring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //@EnableJpaAuditing --> 제거 @SpringBootApplication public class LdwSpringApplication { public static void main(String[] args) { SpringApplication.run(LdwSpringApplication.class, args); } }
Java
복사

JpaConfig.java

package com.citefred.ldwspring.config; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @Configuration @EnableJpaAuditing // JPA Auditing 활성화 public class JpaConfig {}
Java
복사

스프링 시큐리티 적용 후 테스트 코드 정상화 완료

테스트 코드 리팩토링을 통해서 스프링 시큐리티 적용 후 테스트코드 작성 시 신경써야 할 부분들에 대해서 정리 할 수 있었다.
Search
 | Main Page | Category |  Tags | About Me | Contact | Portfolio