@SpringBootTest
The whole app.
Unit tests, and slice tests, check the pieces. But do the pieces work together? At Spring Boot Test starts the whole application, for real.
- Pieces are tested
- Do they fit together?
- @SpringBootTest
Integration tests
At Spring Boot Test starts the full context. Every bean, the database, and data dot sql. At Auto Configure Mock Mvc gives us Mock Mvc, to call it. These tests are slower, so write fewer of them, for the main paths.
| key | value |
|---|---|
| @SpringBootTest | the whole app |
| Includes | all beans, database, data.sql |
| @AutoConfigureMockMvc | call it with MockMvc |
| Write | a few, for main paths |
Controller to database
No mocks this time. The request goes through the controller, the service, the repository, and the database, which was seeded by data dot sql. Book one is Dune. And book ninety nine gives four oh four. Run it. Both tests pass. The whole stack works together.
@SpringBootTest
@AutoConfigureMockMvc
class BookApiTest {
@Autowired MockMvc mvc;
@Test
void readsASeededBook() throws Exception {
mvc.perform(get("/books/1")).andExpect(status().isOk())
.andExpect(content().string("Dune"));
}
@Test
void missingBookIs404() throws Exception {
mvc.perform(get("/books/99")).andExpect(status().isNotFound());
}
}[INFO] Running BookApiTest [INFO] Tests run: 2, 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 data.sql
INSERT INTO book (title, author, price) VALUES
('Dune', 'Frank Herbert', 9.99),
('The Hobbit', 'J.R.R. Tolkien', 8.99),
('Circe', 'Madeline Miller', 10.99),
('Children of Dune', 'Frank Herbert', 8.49),
('Song of Achilles', 'Madeline Miller', 9.49);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueAlso uses _mvn
testWhich test when?
Unit tests, with new, and Mockito, check logic, in milliseconds. Web Mvc Test checks controllers, JSON, and status codes. Data Jpa Test checks queries. And Spring Boot Test checks that everything works together.
| Test | Checks |
|---|---|
| Unit + Mockito | business logic |
| @WebMvcTest | controllers, JSON, status |
| @DataJpaTest | queries |
| @SpringBootTest | everything together |
Summary
At Spring Boot Test starts the whole app, so you can test real paths, from controller to database. Next, some practice.
Key takeaways- @SpringBootTest
- @AutoConfigureMockMvc
- Whole stack