exception-handling - Mockito期望异常

我尝试使用Mockito和Junit测试下面的方法:


@Transactional
@RequestMapping(method=RequestMethod.PUT,value ="/updateEmployer/{empId}")
public @ResponseBody Object updateEmployer(@PathVariable Integer empId,) throws Exception {

 Employee e = EmployeeRepository.findOne(empId);

 for (Department de : e.getDepartement()){
 de.setDepartmentName(e.getName +"_" + de.getName()); 
 }
 EmployeeRepository..saveAndFlush(e);
 return null;
} 

这是方法测试:


@Test // throw java.lang.NullPointerException
 public void updateEmployeeFailureTest() throws Exception {

 mockMvc.perform(
 MockMvcRequestBuilders
 .put("/updateEmployer/{empId}",18) 
 .accept(MediaType.APPLICATION_JSON)).andDo(print()) 

 .andExpect(MockMvcResultMatchers.view().name("errorPage"))
 .andExpect(MockMvcResultMatchers.model().attributeExists("exception"))
 .andExpect(MockMvcResultMatchers.forwardedUrl("/WEB-INF/jsp/errorPage.jsp"))
 .andExpect(MockMvcResultMatchers.status().isInternalServerError()); 

 } 

printStack:


 MockHttpServletRequest:
 HTTP Method = PUT
 Request URI = /updateEmployer/18
 Parameters = {}
 Headers = {Content-Type=[application/json], Accept= application/json]}

 Handler:
 Type = com.controllers.employeeController
 Method = public java.lang.Object com.controllers.employeeController.updateEmployer(java.lang.Integer) throws java.lang.Exception

 Async:
 Was async started = false
 Async result = null

 Resolved Exception:
 ***Type = java.lang.NullPointerException***

 ModelAndView:
 View name = errorPage
 View = null
 Attribute = exception
 ***value = java.lang.NullPointerException***

 FlashMap:

 MockHttpServletResponse:
 Status = 500
 Error message = null
 Headers = {}
 Content type = null
 Body = 
 Forwarded URL = /WEB-INF/jsp/errorPage.jsp
 Redirected URL = null
 Cookies = []

它可以工作,但当我尝试捕获此方法引发的异常时
添加@Test (应为java.lang.NullPointerException.class)出现这个错误:

java.lang.AssertionError : Expected exception : java.lang.NullPointerException

当我尝试获取nullPointerException文本,

java.lang.AssertionError : Model attribute'exception'expected:java.lang.NullPointerException but was:java.lang.NullPointerException

时间:

你需要测试模型的exception属性是否为NullPointerException的实例。

这可以使用Hamcrest匹配器来完成:


 .andExpect(MockMvcResultMatchers.model().attribute(
"exception", 
 Matchers.isA(NullPointerException.class))

...