Spring Boot Database UnitTest

Goal

We would like to Test DAO or Service with Database operations.

But, if we use database for testing directly, we need to prepare a database server and manipulate database for test (dirty).

Is there any way to support not to prepare server for local and not to make dirty data?

H2 In Memory

This is the solution. JPA supports H2 database (h2 is based on java implementation database). H2 support memory mode and we can manipulate data and flush when finishing Unit Test

H2 with Test

application.yml

Prepare test profile

spring:
  profiles: test
  datasource:
    url: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
    username: sa
    password: sa
    driverClassName: org.h2.Driver

build.gradle

Added dependencies

compile("org.springframework.boot:spring-boot-starter-data-jpa")
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("com.h2database:h2")
    

Test

It’s ready. You just write Unit test under test.

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class DataServiceTest {
   // You can call service, dao etc...
}

コメント