Testing JPA entities and repositories using Spring Boot @DataJpaTest

What is @DataJpaTest?

Annotations for using Auto Configuratin for testing entities and repositories. You can easily write a test by using this. It has the following features. -Load the class with @Entitiy and @Repository into ApplicationContext. Classes with other @Service etc. are not loaded. -Rollback the transaction for each test (@Test). Transaction control can be changed. -Use in-memory DB in the test

In addition, TestEntityManager is prepared for manipulating test data in the test class.

See the official documentation for details. 43.3.11 Auto-configured Data JPA Tests

Example

Add a dependency to build.gradle to use the H2 database when testing with JPA.

build.gradle


dependencies {

・ ・ ・
	compile('org.springframework.boot:spring-boot-starter-data-jpa')
	testCompile('org.springframework.boot:spring-boot-starter-test')
	testCompile group: 'com.h2database', name: 'h2', version: '1.4.197'
}

As a sample, create an entity and repository that handles book information as shown below. The following example is written in Kotlin, but the description method is the same in Java.

@Entity
@Table(name = "book")
data class Book(

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY) //ID is automatically generated
        @Column(name = "id")
        var id: Long = 0,

        @Column(name = "title")
        var title: String = "",

        @Column(name = "author")
        var author: String = "",

        @Column
        var price: Long = 0
)

Create the following repository for the above entity.

@Repository
interface BookRepository: JpaRepository<Book, Long> {

    //A method that returns a list of books with the specified author in ascending order of price
    fun findAllByAuthorOrderByPrice(author: String): List<Book>
}

Create a test class. By using TestEntityManager, test data can be stored in DB without using Repository.

import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
import org.springframework.test.context.junit4.SpringRunner

@RunWith(SpringRunner::class)
@DataJpaTest
class BookRepositoryTest {

    @Autowired
    private lateinit var testEntityManager: TestEntityManager

    @Autowired
    private lateinit var bookRepository: BookRepository

    @Test
    fun test() {

        //Test data creation
        testEntityManager.persist(Book(title = "title1", author = "author1", price = 102))
        testEntityManager.persist(Book(title = "title2", author = "author1", price = 101))
        testEntityManager.persist(Book(title = "title3", author = "author2", price = 104))
        testEntityManager.persist(Book(title = "title4", author = "author2", price = 103))

        val foundBooks = bookRepository.findAllByAuthorOrderByPrice("author1")

        //There are two books for author1
        assertThat(foundBooks).size().isEqualTo(2)

        //Search results are in ascending order of price, so title2,Should be in the order of title1
        // title1
        assertThat(foundBooks[0].id).isEqualTo(2)
        assertThat(foundBooks[0].title).isEqualTo("title2")
        assertThat(foundBooks[0].author).isEqualTo("author1")
        assertThat(foundBooks[0].price).isEqualTo(101)

        // title2
        assertThat(foundBooks[1].id).isEqualTo(1)
        assertThat(foundBooks[1].title).isEqualTo("title1")
        assertThat(foundBooks[1].author).isEqualTo("author1")
        assertThat(foundBooks[1].price).isEqualTo(102)

    }
}

Recommended Posts

Testing JPA entities and repositories using Spring Boot @DataJpaTest
8 things to insert into DB using Spring Boot and JPA
Try using DI container with Laravel and Spring Boot
Try using Spring Boot Security
Implement REST API with Spring Boot and JPA (Application Layer)
Implement REST API with Spring Boot and JPA (Infrastructure layer)
Get error information using DefaultErrorAttributes and ErrorAttributeOptions in Spring Boot 2.3
Connect to database with spring boot + spring jpa and CRUD operation
Implement REST API with Spring Boot and JPA (domain layer)
Spring Boot Tutorial Using Spring Security Authentication
Uploading and downloading files using Ajax in Spring Boot (without JQuery)
Spring profile function, and Spring Boot application.properties
Image Spring Boot app using jib-maven-plugin and start it with Docker
Implementation method for multi-data source with Spring boot (Mybatis and Spring Data JPA)
Spring Flash Scope Redirection and Unit Testing
Exists using Specification in Spring Data JPA
HTTPS with Spring Boot and Let's Encrypt
Try using Spring Boot with VS Code
Asynchronous processing with Spring Boot using @Async
Add spring boot and gradle to eclipse
About designing Spring Boot and unit test environment
Spring Boot Whitelabel Error Page and JSON Response
[FCM] Implementation of message transmission using FCM + Spring boot
Output request and response log in Spring Boot
Create a Spring Boot application using IntelliJ IDEA
Various correspondence table of Spring Framework and Spring Boot
Spring Data JPA Entity cross-reference and its notes
Apply Twitter Bootstrap 4 to Spring Boot 2 using Webjars
Spring Boot + Spring Data JPA About multiple table joins
CSRF countermeasure policy and implementation example in REST application using "Spring Boot" + "EXT JS"
Check the behavior of getOne, findById, and query methods in Spring Boot + Spring Data JPA