
Controller에 회원가입 MockMvc로 테스트를 진행 하는 도중에 발견한 오류들이랑 해결한 방법들을 기록 해본다... 자세한 설명들은 추후에 작성할 계획이고 일단은 어떻게 적용을 하였고 해결을 했는가 중점으로 설명을 해보겠다.
가장 먼저 오류를 발견한건 이 에러였다
Failed to load ApplicationContext for [WebMergedContextConfiguration@541d4d9f testClass = com.example.nvcreviewassignment.controller.UserControllerTest, locations = [], classes = [com.example.nvcreviewassignment.NvcReviewAssignmentApplication], contextInitializerClasses = [], activeProfiles = [], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper=true"], contextCustomizers = [org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@495b0487, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@9ae48d0f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@f56ee3c0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@4dc8caa7, [ImportsContextCustomizer@1b31af02 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration, org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration, org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration, org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration, org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration, org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration, org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration, org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration, org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration, org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration, org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration, org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration, org.springframework.boot.test.autoconfigure.web.reactive.WebTestClientAutoConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@18bc345, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@3724af13, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@1c2f17a4, org.springframework.boot.test.context.SpringBootTestAnnotation@5ac351ab], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController' defined in file [/Users/sanguiseong/Documents/sparta/tutor-code/nvc-review-assignment/build/classes/java/main/com/example/nvcreviewassignment/user/controller/UserController.class]: Unsatisfied dependency expressed through constructor parameter 1: No qualifying bean of type 'com.example.nvcreviewassignment.common.jwt.JwtUtil' 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.example.nvcreviewassignment.common.jwt.JwtUtil' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
jwt문제인거 아시고 튜터님이 해결 코드를 주셨다
private final UserService userService;
private final JwtUtil jwtUtil;
public UserController(UserService userService, JwtUtil jwtUtil) {
this.userService = userService;
this.jwtUtil = jwtUtil;
}
private final UserService userService;
private JwtUtil jwtUtil;
public UserController(UserService userService) {
this.userService = userService;
}
public void setBeanFactory(BeanFactory context){
jwtUtil = (JwtUtil)context.getBean(JwtUtil.class);
}
전체 코드를 보고 싶으면 프로젝트 깃허브로 들어오시면 된다
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaAuditingHandler': Cannot resolve reference to bean 'jpaMappingContext' while setting constructor argument
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': JPA metamodel must not be empty
Caused by: java.lang.IllegalArgumentException: JPA metamodel must not be empty
오류 키워드는 Error creating bean with name 'jpaMappingContext'였고 이 또한 튜터님이 추가 코드를 제공 해주셨다
@WebMvcTest(
controllers = {UserController.class},
excludeFilters = {
@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
classes = WebSecurityConfig.class
)
}
)
public class UserControllerTest {
@WebMvcTest(
controllers = {UserController.class},
excludeFilters = {
@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
classes = WebSecurityConfig.class
)
}
)
@MockBean(JpaMetamodelMappingContext.class)
public class UserControllerTest {

자꾸 CLIENT_ERROR가 뜨는것이였다..
@Test
@DisplayName("회원가입")
void 회원가입을_성공_시킬수있다() throws Exception {
// Given
MultiValueMap<String, String> signupRequestForm = new LinkedMultiValueMap<>();
signupRequestForm.add("username", "sollertia4351");
signupRequestForm.add("password", "robbie1234");
signupRequestForm.add("email", "sollertia@sparta.com");
signupRequestForm.add("admin", "false");
// When
// Then
mockMvc.perform(post("/api/auth/signup")
.content(objectMapper.writeValueAsString(signupRequestForm))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().is2xxSuccessful());
}
@Test
@DisplayName("회원가입")
void 회원가입을_성공_시킬수있다() throws Exception {
// Given
// When
// Then
mockMvc.perform(post("/api/auth/signup")
.content(objectMapper.writeValueAsString(new AuthRequestDto("thomas","thomas1234","thomas1234")))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().is2xxSuccessful());
}
@RequestBody를 이용해서 데이터를 받아오는 형식인지라
ObjectMapper이니깐 DTO 객체에 생성자를 넣어줘서 변환을 해줬어야 했다
나는 Map 자료형에 넣어주는 식으로 했었는데 이것은 나중에 프론트엔드랑 결합 후에 해당 페이지를 넘겨주는 String의 방식이였던 것이다!!
이거 해결한다고 많은 시간을 사용을 해서... 이 글을 디테일하게 못 적는거에 대해서 참 슬프다... 나중에 시간이 된다면.. 자세하게 뜯어보면서 풀면서 설명하고 싶다...