Posts Spring Boot Test for JpaRepository
Post
Cancel

Spring Boot Test for JpaRepository

The amount of code that goes into the DAO layer has reduced drastically with the invention of @Repository annotation. Nevertheless, it’s always a good idea to write tests for your DAO layer, just to avoid any unpleasant surprises in the future. There are few perquisites we need to take care of before we dive into writing actual test cases.

  • Recruite in memory database by adding dependency com.h2database:h2
  • Create the database tables in the H2 database and drop them after executing the test cases, by adding spring.jpa.hibernate.ddl-auto=create-drop property to the test.properties file.

In the below test class we inserted a sample Customer object into the database and testing the customerRepo.findByFirstName("John") method. The annotations @ExtendWith(SpringExtension.class) and @DataJpaTest help to instantiate spring context and procure persistent context.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.pradeep.springboot.test.domain.Customer;


@ExtendWith(SpringExtension.class)
@DataJpaTest
@TestPropertySource(locations = "classpath:test.properties")
public class CustomerRepoTest {
    @Autowired
    private CustomerRepo customerRepo;
    
    @Test
    void findByFirstName() {
        Customer customer =  new Customer();
        customer.setId("1234");
        customer.setFirstName("John");
        customer.setLastName("Miller");             
        customerRepo.saveAndFlush(customer);    
        
        
        List<Customer> listOfCustomers = customerRepo.findByFirstName("John");      
        assertThat(listOfCustomers.isEmpty()).isEqualTo(false);
                
    }

}

In this article, we learned about how to test JpaRepository with JUnit and @DataJpaTest and we have used H2 database to spin up a database and destroy it soon after the tests. You can have a look at the example code in my github repository

This post is licensed under CC BY 4.0 by the author.