본문 바로가기
스프링부트와 AWS

#5_Spring Data JPA 테스트 코드 작성하기

by Meaning_ 2021. 8. 8.
728x90
반응형

test 디렉토리에 domain.posts 패키지 작성하고 테스트 클래스는 PostRepositoryTest 이름으로 작성한다.

 

 PostRepositoryTest 에서는 save,findAll 기능을 테스트한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import com.meaningSworld.springboot.domain.posts.Posts;
import com.meaningSworld.springboot.domain.posts.PostsRepository;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
 
@RunWith(SpringRunner.class)
@SpringBootTest
 
public class PostsRepositoryTest {
    @Autowired
    PostsRepository  postsRepository;
 
    @After
    public void cleanup(){
        postsRepository.deleteAll();
    }
 
    @Test
    public void 게시글저장_불러오기(){
        //given
        String title="테스트 게시글";
        String content="테스트 본문";
        postsRepository.save(Posts.builder()
                .title(title)
                .content(content)
                .author("본인 이메일 주소를 적으면 된다!")
                .build());
        //when
        List<Posts>postsList=postsRepository.findAll();
 
        //then
        Posts posts=postsList.get(0);
        assertThat(posts.getTitle()).isEqualTo(title);
        assertThat(posts.getContent()).isEqualTo(content);
    }
}
 
cs

 

@After

- junit 단위 테스트가 끝날때 마다 수행되는 메소드 지정

- 보통은 배포 전 전체 테스트를 수행할 때 테스트 간 데이터 침범을 막기 위해 사용

- 여러 테스트가 동시에 수행되면 테스트용 데이터 베이스인 H2에 데이터가 그대로 남아있어 다음 테스트 실행 시 테스트가 실패할 수 있음.

 

 

postsRepository.save

- 테이블 posts에 insert/update 쿼리를 실행한다

- id값이 있다면 update, 없다면 insert 쿼리가 실행된다. 

 

postsRepository.findAll

 

- 테이블 posts에 있는 모든 데이터를 조회해오는 메소드이다.

 

별다른 설정없이 @SpringBootTest 를 사용할 경우 H2데이터베이스를 자동으로 실행해준다. 


+)H2란? H2 자바로 작성된 관계형 데이터베이스 관리 시스템이다. 자바 애플리케이션에 임베드하거나 클라이언트-서버 모드에서 구동할 수 있다.

 

@Test 옆에 run버튼 누르고 게시글저장_불러오기() 클릭하면 테스트코드가 실행되는 것을 볼 수 있다!


그러면 실제로 실행된 쿼리는 어떤 형태일까?

실행된 쿼리를 로그로 보기 위해 스프링부트에서는 application.properties,application.yml등의 파일로 한줄의 코드를 설정할 수 있도록 지원하고 권장한다.

 

recources 디렉토리 아래에 application.properties 파일을 생성한다.

그 파일 안에 

 

이렇게 작성한다!

 

 

두번째 줄에 create table 쿼리를 보면 id bigint generated by default as identity 라는 옵션으로 생성된다. 이는 H2의 쿼리 문법이 적용되었기 때문이다.H2는 MySQL 쿼리를 수행해도 정상적으로 작동하기 때문에  이후 디버깅을 위해서 출력되는 쿼리 로그를 MySQL 버전으로 변경할 것이다. 이 옵션 역시 application.properties에서 설정이 가능하다. 

2번째줄의 코드를 추가해준다.

 

옵션이 잘 적용된 것을 확인할 수 있다.

728x90
반응형

댓글