[Spring] - Spring Data JPA 테스트코드 작성하기

2025. 2. 6. 22:31·Spring
728x90
반응형
SMALL

앞 포스팅에서 만든 JPA코드를 테스트하는 테스트코드를 만들어보겠다. 

(1) domain.posts 패키지안에 PostsRepositoryTest클래스 생성하기

test 디렉토리에 domain.posts 패키지를 생성하고, 테스트 클래스는  PostsRepositoryTest란 이름으로 생성한다.

위와 같이 생성하였으면 해당 PostsRepositoryTest에서는 save와 findAll기능을 테스트 할 에정이다.

(2) PostsRepositoryTest코드 작성

package com.jojoldu.book.springboot.web.domain.posts;

import com.jojoldu.book.springboot.domain.posts.Posts;
import com.jojoldu.book.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 게시글저장_불러오기() {
        String title = "테스트 게시글";
        String content = "테스트 본문";
        postsRepository.save(Posts.builder()
                .title(title)
                .content(content)
                .author("jangseungwon9819@gmail.com")
                .build());
        //when
        List<Posts> postsList = postsRepository.findAll();

        //then
        Posts posts = postsList.get(0);
        assertThat(posts.getTitle()).isEqualTo(title);
        assertThat(posts.getContent()).isEqualTo(content);
    }
}
  • @After 
    • JUnit에서 단위 테스트가 끝날 때마다 수행되는 메소드를 지정
    • 보통은 배포 전 전체 테스트를 수행할 때 테스트간 데이터 침범을 막기 위해 사용됨
  • postsRepository.save
    • 테이블 posts에 insert/update 쿼리를 실행한다.
    • id값이 있다면 update가, 없다면 insert 쿼리가 실행된다.
  • postsRepository.findAll
    • 테이블 posts에 있는 모든 데이터를 조회해오는 메소드이다.

 

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

위 코드 실행시 역시 H2 데이터베이스를 자동으로 실행한다. 

테스트가 통과되는 것을 확인할 수 있다.

 

(3) 실행된 쿼리 확인하는 방법

실제로 실행된 쿼리는 어떤 형태일까? 라는 의문이다. 

스프링 부트에서는 application.properties, application.yaml등의 파일로 한 줄의 코드로 설정 할 수 있도록 지원한다.

src->main->resources파일 안에 .properties파일을 만들어준다.

spring.jpa.show-sql=true

.properites파일에 위 코드를 추가해준 뒤 실행하면 콘솔에서 쿼리 로그를 확인할 수 있다.

하지만 로그에서 H2문법이 적용된 것을 볼 수 있을건데 

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

 

위 코드까지 추가를 하여 실행하면 쿼리 로그가 MySQL 버전으로 나오는 것을 확인 할 수 있다.

 

다음 포스팅에는 API를 만들어보겠다.

728x90
반응형
LIST

'Spring' 카테고리의 다른 글

[Spring] - 스프링부트 JPA Auditing으로 생성시간/수정시간 자동화하기  (1) 2025.02.13
[Spring] - 스프링 빈(bean)이란?  (0) 2025.02.12
[Spring] - JPA란?  (1) 2025.02.05
[Spring] - 롬복 알아보기 및 설치하기  (1) 2025.02.04
[Spring] - 스프링부트에서 테스트코드 작성하기  (1) 2025.02.03
'Spring' 카테고리의 다른 글
  • [Spring] - 스프링부트 JPA Auditing으로 생성시간/수정시간 자동화하기
  • [Spring] - 스프링 빈(bean)이란?
  • [Spring] - JPA란?
  • [Spring] - 롬복 알아보기 및 설치하기
코린이 파닥거리기
코린이 파닥거리기
    반응형
    250x250
  • 코린이 파닥거리기
    코린이 파닥거리기의 블로그
    코린이 파닥거리기
  • 전체
    오늘
    어제
    • 분류 전체보기 (130) N
      • 백준[파이썬] (57) N
      • Spring (31)
      • CS (1)
      • 자바 (4)
      • 백준[자바] (20)
      • 프로그래머스 (5)
      • 토이프로젝트 (1)
      • SWEA (2)
      • MSA (8) N
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준
    스프링 부트와 AWS로 혼자 구현하는 웹 서비스
    스프링부트
    자바
    MSA
    스프링
    spring
    스프링 클라우드
    재귀
    파이썬
    SWEA
    코딩테스트
    JPA
    SpringBoot
    JWT
    프로그래머스
    AOP
    누적합
    Java
    테스트코드
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
코린이 파닥거리기
[Spring] - Spring Data JPA 테스트코드 작성하기
상단으로

티스토리툴바