我正在尝试用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(应为java.lang.NullPointerException.class)时,我出现了以下错误:
java.lang.AssertionError:预期异常:java.lang.NullPointerException
当我试图将nullPointerException Text作为ModelAndView部分的属性(exception)的值时,我得到了以下错误:
java.lang.AssertionError:应为模型属性"exception":java.lang.NullPointerException,但实际为:java.lang.NullPointerException
有没有一种方法可以使用mockito(mockmvc)来期待抛出的异常或值attribut中的文本(值=java.lang.NullPointerException)或Resolved exception部分中的文本?
任何帮助都将不胜感激
您需要测试模型的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");
...