MockMvc
Requests and JSON checks.
Mock Mvc can send any request, with headers, and a JSON body. And it can check every part of the response.
- Any request
- Headers and JSON
- Check every part
Useful pieces
Get, post, put, and delete, build requests. Content type, and content, set the body. Status checks the status code. Content checks the body. And JSON path digs into the JSON, with dollar dot field.
| Piece | Example |
|---|---|
| Requests | get(), post(), put(), delete() |
| Body | contentType(...).content("{...}") |
| Status | status().isCreated() |
| JSON | jsonPath("$.title").value("Emma") |
POST with JSON
The JSON body is a Java string, with escaped quotes. We script the service's add method. Then we post the JSON, with the JSON content type. We expect two oh one, created, and check two fields, with JSON path. Run it. The test passes.
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired MockMvc mvc;
@MockitoBean BookService service;
@Test
void createsABook() throws Exception {
String json = "{\"title\":\"Emma\",\"author\":\"Austen\",\"price\":6.99}";
when(service.add(any(), any(), anyDouble())).thenReturn(new Book("Emma", "A", 1));
mvc.perform(post("/books").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.title").value("Emma"))
.andExpect(jsonPath("$.author").value("A"));
}
}[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
testTesting validation
This time, the title is blank. Validation should reject it, with four hundred. And verify no interactions checks, the service was never called. Run it. The test passes. So the validation rules are tested too.
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired MockMvc mvc;
@MockitoBean BookService service;
@Test
void rejectsABlankTitle() throws Exception {
String json = "{\"title\":\"\",\"author\":\"Austen\",\"price\":6.99}";
mvc.perform(post("/books").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isBadRequest());
verifyNoInteractions(service);
}
}[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
Mock Mvc builds full requests, and checks status, body, and JSON paths. Next, testing repositories, with at Data Jpa Test.
Key takeaways- post().content(json)
- status().isCreated()
- jsonPath("$.title")