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

Practice: Test the API

Your turn.

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

Let's practise testing. The repository has a query, find by price less than. You'll write a test for it.

  • A query to test
  • findByPriceLessThan
  • Your turn

Test a query

Your turn. Pause the video, and try this. Write a Data Jpa Test, for find by price less than. Save three books, call the query with eight, and check the result. Here is one solution. Two of the three books cost less than eight. And all match checks, that every result really is cheaper. The test passes.

✍️ Exercise: Test a query

@DataJpaTest: save 3 books (9.99, 6.99, 7.49), call findByPriceLessThan(8), assert 2 results, all under 8.

Show hint

assertEquals(2, cheap.size()); assertTrue(cheap.stream().allMatch(...))

Show solution
test/BookRepositoryTest.javajava
@DataJpaTest
class BookRepositoryTest {

    @Autowired BookRepository books;

    @Test
    void findsCheapBooks() {
        books.save(new Book("Dune", "Frank Herbert", 9.99));
        books.save(new Book("Emma", "Jane Austen", 6.99));
        books.save(new Book("Persuasion", "Jane Austen", 7.49));

        List<Book> cheap = books.findByPriceLessThan(8);

        assertEquals(2, cheap.size());
        assertTrue(cheap.stream().allMatch(b -> b.getPrice() < 8));
    }
}
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.price<?
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

What module twelve taught

Unit tests use new, and Mockito, and run in milliseconds. Web Mvc Test, and Mock Mvc, test controllers. Data Jpa Test tests queries, on a real database. And Spring Boot Test checks the whole app.

keyvalue
Unitnew + Mockito
Web@WebMvcTest + MockMvc
Data@DataJpaTest
All@SpringBootTest

Summary

You can now prove that your API works. That's the end of module twelve. Next, production, and our final project.

Key takeaways
  • Unit tests
  • Slice tests
  • Integration tests
Next up: Actuator — health and metrics