BookController { @GetMapping(value = "/books.html", params = "isbn") public String get(@RequestParam("isbn") String isbn, Model model) { bookService.find(isbn) .ifPresent(book -> model.addAttribute("book", book)); return "books/details"; } BookController(BookService bookService); @GetMapping("/books.html") String all(Model model); @GetMapping(value = "/books.html", params = "isbn") String get(@RequestParam("isbn") String isbn, Model model); @PostMapping("/books") Book create(@ModelAttribute Book book);  }
@Test public void shouldReturnListOfBooks() throws Exception { when(bookService.findAll()).thenReturn(Arrays.asList( new Book("123", "Spring 5 Recipes", "Marten Deinum", "Josh Long"), new Book("321", "Pro Spring MVC", "Marten Deinum", "Colin Yates"))); mockMvc.perform(get("/books.html")) .andExpect(status().isOk()) .andExpect(view().name("books/list")) .andExpect(model().attribute("books", Matchers.hasSize(2))); }
@Test public void shouldReturnNoBookWhenNotFound() throws Exception { when(bookService.find(anyString())).thenReturn(Optional.empty()); mockMvc.perform(get("/books.html").param("isbn", "123")) .andExpect(status().isOk()) .andExpect(view().name("books/details")) .andExpect(model().attributeDoesNotExist("book")); }
@Test public void shouldReturnBookWhenFound() throws Exception { Book book = new Book("123", "Spring 5 Recipes", "Marten Deinum", "Josh Long"); when(bookService.find(anyString())).thenReturn( Optional.of(book)); mockMvc.perform(get("/books.html").param("isbn", "123")) .andExpect(status().isOk()) .andExpect(view().name("books/details")) .andExpect(model().attribute("book", Matchers.is(book))); }