我正在尝试使用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(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)预期抛出的异常或值attribut中的文本(value = java.lang.NullPointerException)或Resolved Exception部分中的Text?
非常感谢任何帮助
答案 0 :(得分:1)
您需要测试模型的exception
属性是NullPointerException的实例。
这可以使用Hamcrest匹配器完成:
.andExpect(MockMvcResultMatchers.model().attribute(
"exception",
Matchers.isA(NullPointerException.class))
答案 1 :(得分:0)
更简单的解决方案是通过exception
抓住MvcResult
,如下所示:
...
MvcResult result = mockMvc.perform(...)
...
...
.andReturn();
assertThat(result.getResolvedException(), instanceOf(YourException.class));
assertThat(result.getResolvedException().getMessage(), is("Your exception message");
...