Spring Boot @DataJpaTest Testing : Services and Repo

Testing is a key aspect of building reliable and maintainable applications. In Spring Boot, @DataJpaTest is a specialized test slice that focuses on JPA components such as repositories and entity mappings. It’s incredibly fast and isolated from other parts of your application, making it ideal for testing data access layers.

This post will guide you through using Spring Boot @DataJpaTest Testing for repositories and service layers, including how to mock dependencies and validate behavior.

Spring Boot @DataJpaTest Testing : Services and Repo

๐Ÿ“ฆ Project Setup

Make sure your pom.xml contains:



    
        org.springframework.boot
        spring-boot-starter-data-jpa
    

    
        org.springframework.boot
        spring-boot-starter-test
        test
    

    
        com.h2database
        h2
        test
    


We use H2 in-memory database for testing purposes to keep tests isolated and fast.

๐Ÿ“ Package Structure


com.kscodes.springboot
โ”œโ”€โ”€ model
โ”‚   โ””โ”€โ”€ User.java
โ”œโ”€โ”€ repository
โ”‚   โ””โ”€โ”€ UserRepository.java
โ”œโ”€โ”€ service
โ”‚   โ””โ”€โ”€ UserService.java
โ””โ”€โ”€ test
    โ””โ”€โ”€ repository
        โ””โ”€โ”€ UserRepositoryTest.java

๐Ÿงฑ Entity Example


package com.kscodes.springboot.model;

import jakarta.persistence.*;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    // Getters and Setters
}

๐Ÿ“ฆ Repository Interface


package com.kscodes.springboot.repository;

import com.kscodes.springboot.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserRepository extends JpaRepository {
    Optional findByEmail(String email);
}

โœ… Testing Repository with @DataJpaTest


package com.kscodes.springboot.repository;

import com.kscodes.springboot.model.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
public class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void testFindByEmail() {
        User user = new User();
        user.setName("John");
        user.setEmail("john@example.com");

        userRepository.save(user);

        Optional result = userRepository.findByEmail("john@example.com");
        assertThat(result).isPresent();
        assertThat(result.get().getName()).isEqualTo("John");
    }
}

This is the core of Spring Boot @DataJpaTest Testing: isolated repository logic tested with an in-memory database.

๐Ÿงช Service Layer Example (Optional)

Suppose we want to test UserService that depends on UserRepository. While @DataJpaTest is primarily for repositories, we can use it in combination with @Import.

๐Ÿ’ก UserService


package com.kscodes.springboot.service;

import com.kscodes.springboot.model.User;
import com.kscodes.springboot.repository.UserRepository;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Optional findUserByEmail(String email) {
        return userRepository.findByEmail(email);
    }
}

๐Ÿงช Testing Service with @DataJpaTest + @Import


package com.kscodes.springboot.service;

import com.kscodes.springboot.model.User;
import com.kscodes.springboot.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;

import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
@Import(UserService.class)
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Test
    public void testFindUserByEmail() {
        User user = new User();
        user.setName("Alice");
        user.setEmail("alice@example.com");

        userRepository.save(user);

        Optional result = userService.findUserByEmail("alice@example.com");
        assertThat(result).isPresent();
        assertThat(result.get().getName()).isEqualTo("Alice");
    }
}

โš™๏ธ Configuration Tips

  • @DataJpaTest automatically rolls back transactions after each test.
  • It excludes other Spring beans (like controllers or services) unless explicitly imported via @Import.
  • Use @AutoConfigureTestDatabase(replace = NONE) if you want to test with a real DB.

๐Ÿ“š Summary

In this guide, you learned how to use Spring Boot @DataJpaTest Testing for:

  • Writing isolated tests for repositories
  • Leveraging H2 in-memory database for fast test execution
  • Using @Import to include services in @DataJpaTest