Spring Security 적용 시 controller @WebMvcTest
미해결
Practical Testing: 실용적인 테스트 가이드
안녕하세요 강사님 좋은 강의를 듣고 공부하면서 실무에 적용시키고 있는 중에 두 가지 문제를 만났는데 구글링으로 해결점이 보이지 않아서 강의 내용과 관련 없지만 힌트라도 얻고자 글을 남기게 되었습니다 Spring boot 3.x 이상 버전이고, Spring security가 적용된 프로젝트입니다 첫 번째 문제는 controller 레이어에서 @WebMvcTest를 적용 시에 검증하고자 하는 controller와 주입받은 빈 객체 이외의 뜬금없는 객체 주입 error가 발생하고 있습니다 @V1RestController @RequiredArgsConstructor public class CommonController { private final CommonService commonService; private static final Logger log = LoggerFactory.getLogger(CommonController.class); @GetMapping("/term") public ResponseEntity<TermResDto> getTerm(@RequestParam("account_id") Long id) { return ResponseEntity.ok(commonService.getTerm(id)); } @GetMapping("/message") public ResponseEntity<List<UserMessageResDto>> getUserMessageList(@RequestParam("user_id") Long userId) { return ResponseEntity.ok(commonService.getUserMessageList(userId)); } @GetMapping("/notice") public ResponseEntity<List<UserNoticeResDto>> getUserNoticeList(@RequestParam("user_id") Long userId) { return ResponseEntity.ok(commonService.getNoticeList(userId)); } } class CommonControllerTest extends ControllerTestSupport { @DisplayName("현재 학기 정보를 가져온다") @Test void getCurrentTermInfo() throws Exception { // given String termName = "2023년도 2학기"; LocalDateTime startAt = LocalDateTime.of(2023, 9, 1, 00, 00); LocalDateTime endAt = LocalDateTime.of(2023, 12, 15, 23, 59); TermResDto res = TermResDto.builder() .id(1L) .name(termName) .startAt(startAt) .endAt(endAt) .build(); given(commonService.getTerm(1L)).willReturn(res); // when & then mockMvc.perform( get("/api/v1/term") ) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.code").value("200")) .andExpect(jsonPath("$.status").value("OK")) .andExpect(jsonPath("$.message").value("OK")) .andExpect(jsonPath("$.data").isArray()); } } @WebMvcTest(CommonController.class) @ActiveProfiles("test") public abstract class ControllerTestSupport { @Autowired protected MockMvc mockMvc; @Autowired protected ObjectMapper objectMapper; @MockBean protected CommonService commonService; } 순서대로 controller, controllertest, controllertestsupport 클래스 입니다 java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@2ca54da9 testClass = kr.lineedu.cha.domain.common.controller.CommonControllerTest, locations = [], classes = [kr.lineedu.cha.BaseApplication], contextInitializerClasses = [], activeProfiles = ["test"], propertySourceLocations = [], propertySourceProperties = ["org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper=true"], contextCustomizers = [org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@3012646b, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@416bfba7, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@2aa749... at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authController' defined in file [/Users/luca/Desktop/prod/cha-backend/out/production/classes/kr/lineedu/cha/auth/AuthController.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'kr.lineedu.cha.auth.AuthService' 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 'kr.lineedu.cha.auth.AuthService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1824) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1383) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1337) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:888) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ... 97 more 에러 내용에 보면 전혀 관계가 없는 AuthService에 대한 bean error가 뜨고 있어서 질문드립니다 두 번째는 외부 api와 통신해서 구현되는 로직을 openfeign으로 사용하고 있습니다. BDDMockito로 feign client를 stub해서 테스트를 짜던 중 검증이 부족할 것 같다는 생각에 wiremock을 이용해서 테스트를 진행하려 하는데 best practice를 찾지 못하고 있습니다. 혹시 이에 대한 좋은 자료나 실무에서 사용하는 테스트 케이스가 있을지 궁금해서 질문드립니다
- spring
- tdd
- jpa
- mockito
- 소프트웨어-테스트
- junit5





