사내 레거시 프로젝트가 Spring 4.1 환경이어서 Junit5를 이용하여 Spring 테스트를 사용할 수 없다.
4.3부터 누군가 작성하신 깃헙을 통해(https://github.com/sbrannen/spring-test-junit5) 가능
그리하여 Junit 4 환경의 셋팅을 진행.
의존성 설정 하기
Maven 기준 (pom.xml)
- Junit 4.X
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency
- spring-test
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>스프링버전</version>
<scope>test</scope>
</dependency>
- assertJ (선택)
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.22.0</version>
<scope>test</scope>
</dependency>
테스트 클래스 설정
- 작성할 테스트 클래스에 @RunWith(SpringJUnit4ClassRunner.class) 표기 ⇒ Spring 테스트 설정
- 적용할 Config 맞처줌 @ContextConfiguration
- 예시 (필자는 해당 클래스를 상속할 것이다.)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/*.xml"}) //설정파일 정리
public class BaseJunit4SpringTest {
}
테스트 클래스 작성
- Junit4 기준 테스트 메서드는 public 접근 제한만 허용한다 (Junit5는 모두 허용)
- 관례에 따르면 Junit는 리플렉션 기술을 사용하여 public만 허용했다고 들은 것 같다…
- 자바 선배님들이 남기신 토론의 현장 https://groups.google.com/g/ksug/c/xpJpy8SCrEE (Junit의 테스트 메서드는 왜 Pulic이어야 하는가?)
// BaseJunit4SpringTest 공통부분을 상속 받아 사용했음 public class MsgServiceTest extends BaseJunit4SpringTest { @Test public void 레디스_메시지를_조회한다() { SbizMessage sbizMessage = msgService.retrieveSbizMsg(); assertThat(sbizMessage.getMsgList()).hasSize(3); } }