[英]Handling MethodArgumentNotValidException in Junit testcase?
我正在使用 spring MVC 測試:在我的測試用例中,我傳遞了一個無效的Bar
對象(年齡為零)。 MethodArgumentNotValidException
被拋出,但它嵌套在NestedServletException
中。 無論如何通過現有/自定義HandlerExceptionResolver
從控制器拋出MethodArgumentNotValidException
異常,以便我當前的測試用例checkHit2
通過?
控制器:
@RequestMapping(value="/test", method = RequestMethod.POST, headers="Accept=application/json")
@ResponseBody
public Bar getTables(@Valid @RequestBody Bar id) {
return id;
}
測試用例
@Before
public void setUp() {
mockMvc = standaloneSetup(excelFileUploader).setHandlerExceptionResolvers(new SimpleMappingExceptionResolver()).build();
}
@Test(expected=MethodArgumentNotValidException.class)
public void checkHit2() throws Exception {
Bar b = new Bar(0, "Sfd");
mockMvc.perform(
post("/excel/tablesDetail").contentType(
MediaType.APPLICATION_JSON).content(
TestUtil.convertObjectToJsonBytes(b)));
酒吧
public class Bar {
@JsonProperty("age")
@Min(value =1)
private int age;
public Bar(int age, String name) {
super();
this.age = age;
this.name = name;
}
...
}
Junit輸出
java.lang.Exception: Unexpected exception,
expected<org.springframework.web.bind.MethodArgumentNotValidException> but
was<org.springframework.web.util.NestedServletException>
我有類似的問題,我修復了它從 NestedServletException 擴展我的異常類。 例如:
@RequestMapping(value = "/updateForm/{roleID}", method = RequestMethod.GET)
public String updateForm(@PathVariable Long roleID, Model model, HttpSession session) throws ElementNotFoundException {
Role role = roleService.findOne(roleID);
if (role == null) {
throw new ElementNotFoundException("Role");
}
...
}
我的例外看起來像:
public class ElementNotFoundException extends NestedServletException {
private static final long serialVersionUID = 2689075086409560459L;
private String typeElement;
public ElementNotFoundException(String typeElement) {
super(typeElement);
this.typeElement = typeElement;
}
public String getTypeElement() {
return typeElement;
}
}
所以我的測試是:
@Test(expected = ElementNotFoundException.class)
public void updateForm_elementNotFound_Test() throws Exception {
String roleID = "1";
Mockito.when(roleService.findOne(Long.valueOf(roleID))).thenReturn(null);
mockMvc.perform(get("/role/updateForm/" + roleID)).andExpect(status().isOk()).andExpect(view().name("exception/elementNotFound"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.