본문 바로가기

Java/Spring

[Spring] 게시판 만들기 : 적용한 Spring Data JPA 테스트 코드 작성

반응형

아래의 테스트 코드는 이전글의 Spring Data Jpa를 적용한 후 그에 관련된 테스트 코드를 작성했음을 참고부탁드립니다.

 

✭ [참고] https://chati.tistory.com/68

 

[Spring] 게시판 만들기 : Spring Data Jpa 적용

1. Spring Data Jpa의 의존성 설정 - build.gradle ... dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-data-jpa') //(1)..

chati.tistory.com

 


 

1. Spring Data Jpa 테스트 코드 작성하기

 

(아래의 주소에 테스트 코드를 만든 이유는 실 코드는 main/java/.../domain/posts 에 있게 때문입니다.)

- test/java/.../domain/posts/PostsRepositoryTest.java

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 //(1)
    public void cleanUp() {
        postsRepository.deleteAll();
    }

    @Test
    public void getPost() {
        String title = "테스트 게시글";
        String content = "테스트 본문";

        //(2)
        postsRepository.save(Posts.builder().title(title).content(content).author("chati").build());

        //(3)
        List<Posts> postsList = postsRepository.findAll();

        Posts posts = postsList.get(0);
        assertThat(posts.getTitle()).isEqualTo(title);
        assertThat(posts.getContent()).isEqualTo(content);
    }
}

 

(1) @After

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

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

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

 

(2) postsRepository.save

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

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

 

(3) postsRepository.findAll

  - 테이블 posts에 있는 모든 데이터를 조회

 


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



2. 테스트 코드 실행 결과

 

성공


그렇다면 여기서 문제 !

"실제로 실행된 쿼리는 어떻게 되는거지?"

 

실제로 나는 회사에서 주로 mybatis를 통해 쿼리를 연결한 후 테스트를 하면 로그에 실제 실행된 쿼리가 보인다.

근데 여기 테스트 코드 로그에는 아무리봐도 쿼리가 나온게 없는게 아닌가!

 

알고보니, application 설정 파일에 관련 설정을 해줘야한다.

 

- main/resources/application.properties

spring.jpa.show_sql=true

 

위 설정 후에 실행을 해보면 쿼리 로그를 확인할 수 있다.


 

쿼리 로그

 

그런데 이상한 건 create table을 할때, 분명 내가 설정한 id 옵션이 다르게 설정되어 있었습니다.

 

- 내가 설정한 id 컬럼값

@Entity
public class Posts {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    ...
}

 

이는 H2의 쿼리 문법이 적용되어있기 때문으로 MySQL 쿼리도 정상 동작을 하기때문에 오류 없이 실행되었던 것입니다.

앞으로를 위해 출력되는 로그를 MySQL 버전으로 변경합니다.

 

- main/resources/application.properties

spring.jpa.show_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

 

⌗ 추가 코드

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

 

설정을 완료 후 테스트 코드를 실행하면 아래와 같이 잘 적용된 것을 확인할 수 있습니다.

 

 

반응형

❥ CHATI Github