
@DataJpaTest@WebMvcTest@DataJpaTest는 JPA 관련 테스트를 위한 별도의 컨텍스트를 로드하기 때문에, 다른 테스트 환경과 설정이 다릅니다.@WebMvcTest는 모든 빈을 로드하지 않고 컨트롤러와 관련된 빈만 로드하기 때문에, 테스트 환경의 설정이 조금이라도 다르면 새로운 컨텍스트를 생성하게 됩니다.
@WebMvcTest, @DataJpaTest 클래스를 각각 3개씩 모두 다른 빈을 로드하는 경우에 각기 다른 스프링 어플리케이션이 생성되는 것을 볼 수 있습니다.| 테스트 유형 | 새로 로드되는 조건 |
|---|---|
| DataJpaTest | 엔티티 스캔 경로가 다를 경우, Hibernate 관련 설정이 다를 경우. |
| WebMvcTest | MockBean의 정의가 다를 경우, 테스트 클래스의 컨트롤러 정의가 다를 경우. |
AcceptanceTest, IntegrationTest, WebMvcTest 각각의 테스트 공통 설정을 추상 클래스로 묶어 관리.@DataJpaTest
@ActiveProfiles("test")
class UserControllerTest {
@MockBean
protected UserRepository userRepository;
@Test
void 유저_생성() {
// 테스트 로직 작성
}
@Test
void 유저_조회() {
// 테스트 로직 작성
}
}@DataJpaTest
@ActiveProfiles("test")
class PostRepositoryTest {
@MockBean
protected PostRepository postRepository;
@Test
void 게시글_생성() {
// 테스트 로직 작성
}
@Test
void 게시글_조회() {
// 테스트 로직 작성
}
}@DataJpaTest
@ActiveProfiles("test")
public abstract class RepositoryTest {
@Autowired
protected UserRepository userRepository;
@Autowired
protected PostRepository postRepository;
}class UserRepositoryTest extends RepositoryTest {
@Test
void 유저_저장() {
// 테스트 로직 작성
}
@Test
void 유저_조회() {
// 테스트 로직 작성
}
}class PostRepositoryTest extends RepositoryTest {
@Test
void 게시글_저장() {
// 테스트 로직 작성
}
@Test
void 게시글_조회() {
// 테스트 로직 작성
}
}@WebMvcTest(controllers = UserController.class)
class UserControllerTest {
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@MockBean
protected UserService userService;
@Test
void 유저_생성() {
// 테스트 로직 작성
}
@Test
void 유저_조회() {
// 테스트 로직 작성
}
}@WebMvcTest(controllers = PostController.class)
class PostControllerTest {
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@MockBean
protected PostService postService;
@Test
void 게시글_생성() {
// 테스트 로직 작성
}
@Test
void 게시글_조회() {
// 테스트 로직 작성
}
}@WebMvcTest({
UserController.class,
PostController.class,
})
@ActiveProfiles("test")
public abstract class ControllerTest {
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@MockBean
protected UserService userService;
@MockBean
protected PostService postService;
}class UserControllerTest extends ControllerTest {
@Test
void 유저_생성() {
// 테스트 로직 작성
}
@Test
void 유저_조회() {
// 테스트 로직 작성
}
}class PostontrollerTest extends ControllerTest {
@Test
void 게시글_생성() {
// 테스트 로직 작성
}
@Test
void 게시글_조회() {
// 테스트 로직 작성
}
}