BookController { @GetMapping("/{isbn}") public ResponseEntity<Book> get(@PathVariable("isbn") String isbn) { return bookService.find(isbn) .map(ResponseEntity::ok) .orElse(ResponseEntity.notFound().build()); } BookController(BookService bookService); @GetMapping Iterable<Book> all(); @GetMapping("/{isbn}") ResponseEntity<Book> get(@PathVariable("isbn") String isbn); @PostMapping ResponseEntity<Book> create(@RequestBody Book book,
                                     UriComponentsBuilder uriBuilder);  }
@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")) .andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))) .andExpect(MockMvcResultMatchers.jsonPath("$[*].isbn", Matchers.containsInAnyOrder("123", "321"))) .andExpect(MockMvcResultMatchers.jsonPath("$[*].title", Matchers.containsInAnyOrder("Spring 5 Recipes", "Pro Spring MVC"))); }
@Test public void shouldReturn404WhenBookNotFound() throws Exception { when(bookService.find(anyString())).thenReturn(Optional.empty()); mockMvc.perform(get("/books/123")) .andExpect(status().isNotFound()); }
@Test public void shouldReturnBookWhenFound() throws Exception { when(bookService.find(anyString())).thenReturn( Optional.of(new Book("123", "Spring 5 Recipes", "Marten Deinum", "Josh Long"))); mockMvc.perform(get("/books/123")) .andExpect(status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.isbn", Matchers.equalTo("123"))) .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.equalTo("Spring 5 Recipes"))); }