본문 바로가기
Programming/Languages (Java, etc)

[JPA] Spring Boot JPA 초간단 CRUD 테스트 작성하기

by kghworks 2023. 11. 29.

목차

  • Spring initializr
  • 의존성 추가
  • Datasource / Hibernate 설정
  • Entity 정의
  • 테스트 추가
  • 실행

 

개발환경

  • Java 17
  • Spring Boot 3.2.0
  • Gradle 8.4
  • H2 Database
  • Spring Data JPA
  • Lombok

spring initializr

아래에서 개발환경에 맞게 스프링 프로젝트 생성

 

https://start.spring.io/

 

 

의존성 추가

plugins {
	id 'java'
	id 'org.springframework.boot' version '3.2.0'
	id 'io.spring.dependency-management' version '1.1.4'
}

group = 'com.sample.jpa'
version = '0.0.1-SNAPSHOT'

java {
	sourceCompatibility = '17'
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter'
	implementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.hamcrest:hamcrest:2.2'

	runtimeOnly 'com.h2database:h2'

	annotationProcessor "jakarta.annotation:jakarta.annotation-api"
	annotationProcessor "jakarta.persistence:jakarta.persistence-api"
	implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'

}

tasks.named('test') {
	useJUnitPlatform()
}

 

Datasource / Hibernate 설정

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:testdb
    username: username
    password: password
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect
        format_sql: true
        show_sql: true

 

 

Entity 정의

package com.sample.jpa;

import jakarta.persistence.*;
import lombok.Data;
import lombok.ToString;

@Data
@ToString
@Entity
@Table(name = "Member")
public class Member {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Column(name = "name")
    private String name;
}

 

 

테스트 추가

package com.sample.jpa;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

@SpringBootTest
public class CrudTest {

    @PersistenceContext
    private EntityManager entityManager;

    @Test
    @DisplayName("Create")
    @Transactional
    public void create() {

        Member member = new Member();
        member.setName("Karina");
        entityManager.persist(member);
        entityManager.flush();
        entityManager.clear();

        Member saved = entityManager.find(Member.class, member.getId());
        assertThat(saved.getName(), is("Karina"));
    }

    public Member setUp() {
        Member member = new Member();
        member.setName("Karina");
        entityManager.persist(member);
        entityManager.flush();
        entityManager.clear();
        return member;
    }

    @Test
    @DisplayName("Read")
    @Transactional(readOnly = true)
    public void read() {

        long generatedId = setUp().getId();

        Member generated = entityManager.find(Member.class, generatedId);

        assertThat(generated, is(notNullValue()));
        assertThat(generated.getId(), is(generatedId));
        assertThat(generated.getName(), is("Karina"));
    }


    @Test
    @DisplayName("Update")
    @Transactional
    public void update() {


        long generatedId = setUp().getId();

        Member generated = entityManager.find(Member.class, generatedId);

        generated.setName("Karina (updated)");
        entityManager.persist(generated);
        entityManager.flush();
        entityManager.clear();

        Member updated = entityManager.find(Member.class, generated.getId());
        assertThat(updated.getName(), is("Karina (updated)"));
    }

    @Test
    @DisplayName("Delete")
    @Transactional
    public void delete() {

        long generatedId = setUp().getId();

        Member generated = entityManager.find(Member.class, generatedId);

        entityManager.remove(generated);
        entityManager.flush();
        entityManager.clear();

        Member deleted = entityManager.find(Member.class, generatedId);

        assertThat(deleted, is(nullValue()));
    }


}

 

실행

Intellij JUnit 5 실행

 

댓글