AI Hints
Home›Spring Boot Tutorial›@DataJpaTest, @SpringBootTest and Practice: Test the API
Spring Boot · Lesson 106 of 120

@DataJpaTest

Test the database layer.

⏱ 2 min read▶ Video at 2:20:50🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Our query methods are only declarations. We can't unit test them with new. We need a real database, and Spring Data. At Data Jpa Test gives us exactly that.

  • Queries are declarations
  • Need a real database
  • @DataJpaTest

A JPA slice

At Data Jpa Test starts only JPA, the repositories, and an in memory database. No web layer, and no services. Each test runs in a transaction, that's rolled back at the end. So every test starts with a clean, empty database.

keyvalue
StartsJPA + repositories + H2
Skipsweb, services
Each testrolled back
Resulta clean database

Testing a query

The repository is injected. We save three books, two by Herbert. Then we run our query, and check the results. Two books, with the cheapest first. Run it. The query works, against a real database.

test/BookRepositoryTest.javajava
@DataJpaTest
class BookRepositoryTest {

    @Autowired BookRepository books;

    @Test
    void findsAnAuthorsBooksByPrice() {
        books.save(new Book("Dune", "Frank Herbert", 9.99));
        books.save(new Book("Children of Dune", "Frank Herbert", 8.49));
        books.save(new Book("Emma", "Jane Austen", 6.99));

        List<Book> found = books.findByAuthorOrderByPrice("Frank Herbert");

        assertEquals(2, found.size());
        assertEquals("Children of Dune", found.get(0).getTitle());
    }
}
Output
[INFO] Running BookRepositoryTest
Hibernate: drop table if exists book cascade
Hibernate: create table book (price float(53) not null, id bigint generated by default
as identity, author varchar(255), title varchar(255), primary key (id))
Hibernate: insert into book (author,price,title,id) values (?,?,?,default)
Hibernate: insert into book (author,price,title,id) values (?,?,?,default)
Hibernate: insert into book (author,price,title,id) values (?,?,?,default)
Hibernate: select b1_0.id,b1_0.author,b1_0.price,b1_0.title from book b1_0 where
b1_0.author=? order by b1_0.price
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}

    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }

    @Override
    public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorOrderByPrice(String author);

    List<Book> findByPriceLessThan(double max);
}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
Also uses BookService.java
@Service
public class BookService {

    private final BookRepository books;

    public BookService(BookRepository books) { this.books = books; }

    public String title(long id) {
        return books.findById(id).map(Book::getTitle)
                    .orElseThrow(() -> new BookNotFoundException(id));
    }

    public Book add(String title, String author, double price) {
        return books.save(new Book(title, author, price));
    }
}
Also uses NewBook.java
public record NewBook(@NotBlank String title, @NotBlank String author, @Positive double price) {}
Also uses BookController.java
@RestController
@RequestMapping("/books")
public class BookController {

    private final BookService service;

    public BookController(BookService service) { this.service = service; }

    @GetMapping("/{id}")
    public String title(@PathVariable long id) { return service.title(id); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Book add(@Valid @RequestBody NewBook b) {
        return service.add(b.title(), b.author(), b.price());
    }
}
Also uses _mvn
test

Summary

At Data Jpa Test starts the JPA layer with an in memory database, and rolls back after every test. Next, testing the whole app.

Key takeaways
  • @DataJpaTest
  • Real queries
  • Rolled back
Next up: @SpringBootTest — the whole app