[Chapter 07] 테스트클래스 빈 주입방식(416p) #68
Answered
by
Irisation23
Youngju-Jang
asked this question in
Chapter 07. Spring AOP, Testing, and Auto Confiugration
-
테스트클래스 빈 주입방식(416p)
@SpringBootTest
class HotelDisplayServiceTest {
private final HotelDisplayService hotelDisplayService;
private final ApplicationContext applicationContext;
@Autowired // 생성자주입방식으로 하려면 생성자에 Autowired필수
public HotelDisplayServiceTest(HotelDisplayService hotelDisplayService,
ApplicationContext applicationContext) {
this.hotelDisplayService = hotelDisplayService;
this.applicationContext = applicationContext;
} TestPropertySource 설정 (p421)@SpringBootTest
//@Import (value={TestConfig.class}
@ContextConfiguration(classes = TestConfig.class) // Import 나 이거 사용
@TestPropertySource(locations = "classpath:application-test.yaml") // <<<
class HotelRoomDisplayServiceTest01 { spring:
main:
allow-bean-definition-overriding: true
|
Beta Was this translation helpful? Give feedback.
Answered by
Irisation23
Oct 21, 2023
Replies: 3 comments 1 reply
-
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Youngju-Jang
-
2번 저 부분은 저도 처음에 오류가 났다가 @TestPropertySource(locations = "classpath:application-test.yaml")
// 이 부분을
@TestPropertySource(properties = {"spring.config.location = classpath:application-test.yaml"})
// 이렇게 바꾸니까 그냥 main 폴더에서만 yaml 설정해줘도 되긴하던데 이게 해결 방법이 맞는지는 모르겠습니다 |
Beta Was this translation helpful? Give feedback.
1 reply
-
금주 CheckPoint
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
테스트클래스 빈 주입방식(416p) 에 대한 질문의 답을 드리고자 합니다.
먼저 테스트 클래스에서의 생성자 빈 주입 에러와 프로덕션 코드에서의 빈 주입 에러에 대해 비교 해 봅시다.
NoParameterResolver
에러가 발생함NoSuchBeanException
에러가 발생함자 해당 에러를 확인 해 보면 차이점이 있습니다.
테스트 코드에서 발생하는 에러는
NoParameterResolver
, 프로덕션 코드에서의 빈 주입 에러는NoSuchBeanException
입니다.이는 스프링 빈 주입의 방식이 프로덕션 코드와 테스트 코드간에 다른 방법을 취하고 있기 때문입니다.
생성자 매개변수의 경우 프로덕션 코드라면 Spring IoC 컨테이너가 이를 해결합니다.
스프링 프레임워크의 ApplicationContext는 등록할 빈들을 찾아서 저장했다가 적절한 시점에 빈을 생성자에 주입합니다.
그러나, 테스트 코드는 조금 다릅니다.
테스트 프레임워크에서의 생성자 매개변수 관리는 스프링 컨테이너가 아닌
Jupiter
가 담당합니다.따라서
@Autowired
를 명시적으로 선언해야Jupiter
가 Spring Container에게 빈 주입을 요청할 수 있게 됩니다.테스트 프레임워크에서 프레임워크의 주체는
Jupiter
이기 때문에 생성자 주입을 한들 찾…