본문 바로가기

Spring/Test

[Spring] [Error] 스프링 사용해서 테스트 할 때, 붙여줘야 하는 어노테이션 / 에러 내용 : Neither @ContextConfiguration nor @ContextHierarchy found for test class

스프링 테스트를 돌렸는데, 다음과 같은 에러가 발생했다.

스프링 빈 컨테이너가 생성될 때, 사용할 설정 파일을 지정해달라는 것이였다.

9월 24, 2022 10:52:47 오후 org.springframework.test.context.support.AbstractTestContextBootstrapper buildDefaultMergedContextConfiguration
정보: Neither @ContextConfiguration nor @ContextHierarchy found for test class [org.example.guestbookupgrade.dao.GuestbookDaoTest], using DelegatingSmartContextLoader
9월 24, 2022 10:52:47 오후 org.springframework.test.context.support.AbstractContextLoader generateDefaultLocations
정보: Could not detect default resource locations for test class [org.example.guestbookupgrade.dao.GuestbookDaoTest]: no resource found for suffixes {-context.xml}.

 

내 코드가 다음과 같았는데,

@ExtendWith(SpringExtension.class)
class GuestbookDaoTest {

 

아래와 같이 @ContextConfiguration를 추가해주었다.

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = ApplicationConfig.class) // 스프링 컨테이너의 설정 파일을 java config로 했기 때문에 class 지정
class GuestbookDaoTest {

 

Spring으로 테스트 할 때 붙여줘야 하는 어노테이션

@ExtendWith

확장 기능을 제공하는 어노테이션입니다.

Spring을 사용할 경우 @ExtendWith(SpringExtension.class)와 같이 사용합니다. 이 클래스는 내부적으로 스프링 컨테이너를 생성해줍니다.

 

@ContextConfiguration

동일함(내부적으로 생성된 스프링 빈 컨테이너가 사용할 설정파일을 지정할 때 사용합니다.

 

생성된 스프링 컨테이너에 스프링 빈을 추가하기 위해서는 application-context.xml 파일과 같은 설정 파일을 읽어야 하는데, 이런 설정파일을 로드하는 어노테이션이 ContextConfiguration이다.

(참고로, 현재 우리는 xml파일로 빈을 등록하지 않고, "java config 클래스로 빈을 등록"하고 있다. 즉, java config 클래스로 스프링 컨테이너 설정을 지정해주고 있다. 따라서 파라미터로 xml파일을 등록하는 것이 아니라, java config 클래스를 등록하면 된다!!)

 

만약 스프링 컨테이너가 필요 없다면, 즉, 스프링 빈 팩토리에서 빈을 로드하는 것이 아닌, 직접 new로 객체를 생성해가며 테스트 코드를 작성할 것이라면 위의 어노테이션을 제거해도 된다.

 

[의문점]

  1. @ContextConfiguration(class? location?)
    • 이건, 클래스를 지정하는 것일까 아니면 xml 파일을 지정하는 것인가?
    • Cannot process locations AND classes for context configuration 이라는 에러가 발생한 것으로 보아, 둘 중 하나만 지정하는 것이다.
    • [결론] - 현재 우리는 java config 클래스로 스프링 컨테이너의 설정을 지정해주므로, class를 넣어주면 된다.