0

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.

  • What is the error? – Compass Jun 01 '18 at 17:53
  • [This](https://stackoverflow.com/questions/17743141/mock-class-in-class-under-test) question indirectly answers your question. You need to add a way to provide a mock implementation of `BookService` to your `BookRepository` class. – DavidW Jun 01 '18 at 17:57
  • I have mocked the bookService using @Mock annotation and calling when().thenthrow() helps me in achieving it. – Rishabh Sharma Jun 01 '18 at 18:11
  • @Compass Error is my test cases are running successfully with both the status code ( 200 or 500 ). Instead of that it should fail it one of them. Other print statements ( hello2,hello3,hello4 ) should be printed if uncommented. These both things are not happening. – Rishabh Sharma Jun 01 '18 at 18:13
  • Have you tried putting a try catch around the `when(bookService.findBookByName(any())).thenThrow(new Exception());` to see what exception that is actually throwing? – Paul Warren Jun 02 '18 at 05:55

0 Answers0