2

我正在尝试使用 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 Text 作为 ModelAndView 部分的属性(异常)的值时,我收到此错误:

java.lang.AssertionError:预期模型属性“异常”:java.lang.NullPointerException 但为:java.lang.NullPointerException

有没有办法使用mockito(mockmvc)期望抛出异常或值属性(value = java.lang.NullPointerException)或Resolved Exception部分中的文本?

任何帮助都感激不尽

4

2 回答 2

1

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

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

 .andExpect(MockMvcResultMatchers.model().attribute(
     "exception", 
      Matchers.isA(NullPointerException.class))
于 2015-02-24T13:59:00.287 回答
0

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

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

assertThat(result.getResolvedException(), instanceOf(YourException.class));
assertThat(result.getResolvedException().getMessage(), is("Your exception message");
...
于 2017-05-24T15:31:28.873 回答