• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

Spring Security 적용 시 controller @WebMvcTest

23.11.16 14:21 작성 23.11.16 14:21 수정 조회수 372

0

안녕하세요 강사님 좋은 강의를 듣고 공부하면서 실무에 적용시키고 있는 중에 두 가지 문제를 만났는데 구글링으로 해결점이 보이지 않아서 강의 내용과 관련 없지만 힌트라도 얻고자 글을 남기게 되었습니다

Spring boot 3.x 이상 버전이고, Spring security가 적용된 프로젝트입니다

  1. 첫 번째 문제는 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가 뜨고 있어서 질문드립니다

  1. 두 번째는 외부 api와 통신해서 구현되는 로직을 openfeign으로 사용하고 있습니다. BDDMockito로 feign client를 stub해서 테스트를 짜던 중 검증이 부족할 것 같다는 생각에 wiremock을 이용해서 테스트를 진행하려 하는데 best practice를 찾지 못하고 있습니다. 혹시 이에 대한 좋은 자료나 실무에서 사용하는 테스트 케이스가 있을지 궁금해서 질문드립니다

답변 2

·

답변을 작성해보세요.

0

안녕하세요, luca 님! :)

  1. @WebMvcTest가 뜨면서 필요한 스프링 빈들만 등록되어 스프링 컨텍스트가 올라갈텐데요.
    이 경우 AutoController를 등록하려고 하는 과정에서 AutoService 빈이 없어서 나는 에러 같네요.
    이런 경우 원인이 다양할 수 있어서 올려주신 내용만 가지고는 확인할 수가 없고, 어느 부분 때문에 AutoController가 빈으로 등록되려고 하는지 프로젝트 전체적으로 살펴보아야 합니다.
    한번 시도해 보시고 말씀 주세요. ㅎㅎ

  2. Wiremock 에 대한건 저도 사용해본 적은 없어서 잘 모르겠네요. 그래도 공식 문서가 잘 나와있는 것 같아서 해당 예제 기반으로 적용해보심이 어떨까 합니다.

감사합니다. :)

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.11.18

안녕하세요 Luca 님, 인프런 AI 인턴이에요.
1. 첫 번째 문제인 빈 주입 오류는 @WebMvcTest 어노테이션을 사용할 때 해당 컨트롤러와 관련된 빈들만 로드되므로, @WebMvcTest(CommonController.class)를 사용할 경우 CommonService 빈이 주입되지 않아 오류가 발생할 수 있습니다. 이 문제를 해결하기 위해 CommonControllerTest 클래스에서 @MockBean 어노테이션을 사용하여 CommonService 빈을 목 객체로 등록하면 됩니다. 아래와 같이 수정해보세요:

@WebMvcTest(CommonController.class)
@ActiveProfiles("test")
public class CommonControllerTest extends ControllerTestSupport {

    @MockBean
    private CommonService commonService;

    // 테스트 메소드 코드

}
  1. 두 번째 문제인 WireMock을 사용한 외부 API 통신에 대해서는 아래의 링크를 참고하시면 도움이 될 수 있습니다.