@WebMvcTest
Test the web layer.
Controllers deal with URLs, JSON, and status codes. To test those, we need part of Spring running. But only the web part.
- URLs, JSON, status codes
- Need part of Spring
- Only the web part
A slice test
At Web Mvc Test starts only the web layer, for one controller. Services and repositories are not created. So we replace the service with a mock, using at Mockito Bean. And Mock Mvc sends fake requests, without a real server.
| key | value |
|---|---|
| @WebMvcTest(X.class) | web layer only |
| @MockitoBean | a mock in the context |
| MockMvc | fake requests |
| No server | fast |
Testing a GET
At Web Mvc Test loads just the book controller. Mock Mvc is injected, and the service is a mock bean. We script the service, then perform GET slash books slash one. And we expect status ok, and the body Dune. Run it. The test passes.
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired MockMvc mvc;
@MockitoBean BookService service;
@Test
void returnsTheTitle() throws Exception {
when(service.title(1L)).thenReturn("Dune");
mvc.perform(get("/books/1"))
.andExpect(status().isOk())
.andExpect(content().string("Dune"));
}
}[INFO] Running BookControllerTest [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
testErrors in the web layer
Now the mock throws Book Not Found Exception. Is not found checks for four oh four. And verify checks the controller called the service. Run it. The not found status really works, through the web layer.
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired MockMvc mvc;
@MockitoBean BookService service;
@Test
void missingBookIs404() throws Exception {
when(service.title(9L)).thenThrow(new BookNotFoundException(9));
mvc.perform(get("/books/9")).andExpect(status().isNotFound());
verify(service).title(9L);
}
}[INFO] Running BookControllerTest [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
testSummary
At Web Mvc Test starts only the web layer, at Mockito Bean replaces the service, and Mock Mvc sends fake requests. Next, more Mock Mvc.
Key takeaways- @WebMvcTest
- @MockitoBean
- mvc.perform(get(...))