[Spring] 슬라이스 테스트

zini9188·2023년 3월 3일
0

Spring

목록 보기
30/33

API 계층 테스트

클라이언트의 요청을 받아들이는 핸들러인 Controller가 테스트 대상의 대부분

@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTestDefaultStructur{
	@Autowired
    private MockMvc mockMvc;
    
    @Autowired
    private Gson gson
    
    @Test
    public void postMemberTest() {
    	// given
        MemberDto.Post post = new MemberDto.Post("hgd@gmail.com",
        										 "홍길동",
                                                 "010-1234-5678");                                                 
        String content = gson.toJson(post);
        // when
        ResultActions actions =
                mockMvc.perform(post("/v11/members") 
                						.accept(MediaType.APPLICATION_JSON)
                                        .contentType(MediaType.APPLICATION_JSON)
                                        .content(content));
        // then
        actions.andExpect(status().isCreated())
               .andExpect(header().string("Location", is(startsWith("/v11/members/"))));    
    }
}
  • @SpringBootTest: 스프링 부트 기반의 애플리케이션을 테스트하기 위한 Application Context를 생성해줌

  • @AutoConfigureMockMvc: Controller 테스트를 위한 애플리케이션의 자동 구성 작업을 해줌

  • MockMvc: Tomcat과 같은 서버를 실행하지 않고 Controller를 테스트할 수 있는 환경을 지원

  • Gson: Json 포맷으로 객체를 변환하기 쉽게 도와주는 JSON 변환 라이브러리

    • build.gradle dependencies에 implementation 'com.google.code.gson:gson' 추가 필요
  • Given: Postman으로 제공하던 request body를 생성

    • Gson 객체로 MemberDto.Post 객체를 JSON 포맷으로 변환해줌
  • When: MockMvc 객체를 통해 요청 URI와 HTTP 메서드 등을 지정하여, 테스트용 request body를 추가하여 request를 수행

    • post(): request URL 설정
    • accept(): 클라이언트쪽에서 리턴 받을 응답 데이터 타입으로 JSON 타입을 설정
    • contentType(): 서버쪽에서 처리 가능한 Content Type으로 JSON 타입을 설정
    • content(): request body 데이터를 설정
  • Then: Controller에서 전달 받은 HTTP Status와 response body 데이터를 통해 검증 작업을 진행

    • andExpect(): 파라미터로 입력한 매처로 예상되는 기대 결과를 검증
    • status().isCreated(): response status가 201(Created)인지 매치
    • header().string("Location", ..): Location의 문자열 값을 검증

@WebMvcTest를 이용한 Controller 테스트

전통적인 방법으로 @WebMvcTest 애너테이션이 존재하지만, Controller에서 의존하는 컴포넌트들을 모두 일일이 설정해줘야 한다는 단점을 가지고 있다.

데이터 액세스 계층 테스트

데이터 액세스 계층 테스트에서 지켜야 하는 규칙

  • DB의 상태를 테스트 케이스 실행 이전으로 되돌려서 깨끗하게 만든다.

각각의 테스트의 독립성을 보장해주어야 하기 때문이다.

회원 정보 저장 테스트하기

@DataJpaTest
public class MemberRepositoryTest{
	@Autowired
    private MemberRepository memberRepository;
    
    @Test
    public void saveMemberTest(){
    	// given
        Member member = new Member();
        member.setEmail("abc@naver.com");
        member.setName("홍길동");
        member.setPhone("010-1234-1234");
        
        // when
        Member savedMember = memberRepository.save(member);
        
        // then
        assertNotNull(savedMember);
        assertTrue(member.getEmail().equals(savedMember.getEmail())); 
        assertTrue(member.getEmail().equals(savedMember.getName())); 
		assertTrue(member.getEmail().equals(savedMember.getPhone()));        
    }   
}
  • @DataJpaTest: MemberRepository의 기능을 정상적으로 사용하기 위한 Configuration을 스프링에서 자동으로 추가해준다.
    • @Transactional 애너테이션을 포함하기 때문에 하나의 테스트 케이스 실행이 종료되는 시점에 데이터베이스에 저장된 데이터는 rollback 처리가 된다.
  • assertNotNull(): Member 객체가 null인지를 검증

@DataJpaTest의 역할

@DataJpaTest 애너테이션은 아래와 같은 자동 구성 기능들을 임포트하여 테스트가 가능하도록 만들어준다.

그러나 Spring Boot의 모든 자동 구성을 활성화하진 않으며, 데이터 액세스 계층에 필요한 자동 구성만을 활성화한다.

org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration 
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration 
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration 
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration 
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration 
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration 
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration 
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration 
org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration 
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration 
org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration 
org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration

Spring JDBC, Spring DATA JDBC에서의 테스트 환경

각각의 환경에서는 @JdbcTest, @DataJdbcTest 애너테이션을 활용하여 테스트를 진행할 수 있다.

profile
백엔드를 지망하는 개발자

0개의 댓글