Mockito thenThrow()错误

时间:2018-06-01 17:37:19

标签: java spring spring-mvc junit

我正在使用spring开发一个简单的Restful api并尝试遵循TDD模型。我有一个BookController,它按细节返回书籍。它在控制器内部有一个服务调用,我在Test类中进行了模拟。

 @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();
        }
}

并且测试看起来

 @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");
}

当我运行或调试测试用例时,在().thnthrow()之后它没有运行。在上面的代码中,如果我指定打印的最后一个语句hello1。并且无论is2xx还是is5xx测试用例都通过了。请帮我理解这个问题。

0 个答案:

没有答案