I am developing a simple Restful api using spring and trying to follow the TDD model for it. I have a BookController which returns the books by details. It has one service call inside the controller which I have mocked in the Test class.
@Autowired
BookService bookService;
@RequestMapping(value = "/books/getDetails/{bookName}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseEntity<Books> getBooksDetailsByName(@PathVariable(value = "bookName") String bookName){
try {
Books resultBooks = bookService.findBookByName(bookName);
if (resultBooks != null) {
return new ResponseEntity<>(resultBooks, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
catch(Exception e){
throw new RuntimeException();
}
}
and the test looks
@Test(expected = Exception.class)
public void getBookDetails_shouldReturn500() throws Exception {
String bookName = "First";
//System.out.println("hello1");
when(bookService.findBookByName(any())).thenThrow(new Exception());
//System.out.println("hello2");
ResponseEntity<Books> responseEntity = bookController.getBooksDetailsByName(bookName);
//System.out.println("hello3");
Assert.assertTrue(responseEntity.getStatusCode().is2xxSuccessful());
//System.out.println("hello4");
}
When I am running or debugging the test case, it's not running after when().thenthrow(). In the above code if I specify the last statement that is printed it hello1. And irrespective of is2xx or is5xx test case gets passed. Please help me understand the problem.