AI Hints
Home›Spring Boot Tutorial›Mockito, @WebMvcTest and MockMvc
Spring Boot · Lesson 103 of 120

Mockito

Fake dependencies.

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

Our book service needs a repository, and the repository needs a database. For a unit test, we don't want a real database. We want a fake repository, that we control.

  • The service needs a repository
  • No real database
  • A fake we control

Mocks

Mockito creates mocks, fake objects that look like the real thing. Mock, with a class, creates one. When, then return, tells it what to answer. And verify checks that a method was called.

keyvalue
mock(Repo.class)a fake object
when(...).thenReturn(...)script an answer
verify(mock).save(...)was it called?
No databasepure Java

The service under test

Title loads a book by id, and returns its title, or throws not found. Add creates a book, and saves it.

BookService.javajava
@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));
    }
}

Scripted answers

We create a mock repository, and pass it to the service. In the first test, find by id one answers with Dune. In the second, find by id nine answers empty, so the service must throw. Run it. Both tests pass, without any database.

test/BookServiceTest.javajava
class BookServiceTest {

    BookRepository repo = mock(BookRepository.class);
    BookService service = new BookService(repo);

    @Test
    void findsTheTitle() {
        when(repo.findById(1L)).thenReturn(Optional.of(new Book("Dune", "Herbert", 9.99)));
        assertEquals("Dune", service.title(1L));
    }

    @Test
    void missingBookThrows() {
        when(repo.findById(9L)).thenReturn(Optional.empty());
        assertThrows(BookNotFoundException.class, () -> service.title(9L));
    }
}
Output
[INFO] Running BookServiceTest
[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> {
}
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

Verifying calls

Here, add returns nothing interesting, so we check what it did. Verify checks that save was called, with any Book. And never checks that delete was not called. Run it. The test passes.

test/BookServiceTest.javajava
class BookServiceTest {

    BookRepository repo = mock(BookRepository.class);
    BookService service = new BookService(repo);

    @Test
    void addSavesTheBook() {
        service.add("Emma", "Jane Austen", 6.99);
        verify(repo).save(any(Book.class));
        verify(repo, never()).deleteById(anyLong());
    }
}
Output
[INFO] Running BookServiceTest
[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> {
}
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

Mockito mocks replace real dependencies. Script answers with when, then return, and check calls with verify. Next, testing controllers, with at Web Mvc Test.

Key takeaways
  • mock()
  • when().thenReturn()
  • verify()
Next up: @WebMvcTest — test the web layer