Mockito 期待一个例外

Mockito Expect an Exception

我正在尝试使用 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());       

    }   

打印堆栈:

 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 (expected= java.lang.NullPointerException.class) 我有这个错误:

java.lang.AssertionError:预期异常:java.lang.NullPointerException

当我尝试获取 nullPointerException 文本作为 ModelAndView 部分的属性(异常)的值时,出现此错误:

java.lang.AssertionError: 模型属性 'exception' expected:java.lang.NullPointerException 但 was:java.lang.NullPointerException

有没有办法使用 mockito (mockmvc) 来预期抛出的异常或值属性中的文本 (value = java.lang.NullPointerException) 或“已解决的异常”部分中的文本?

任何帮助将不胜感激

您需要测试模型的 exception 属性是 NullPointerException 的实例。

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

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

一个更简单的解决方案是通过 MvcResult 捕获 exception,如下所示:

...
MvcResult result = mockMvc.perform(...)
        ...
        ...
        .andReturn();

assertThat(result.getResolvedException(), instanceOf(YourException.class));
assertThat(result.getResolvedException().getMessage(), is("Your exception message");
...