我正在使用 spring MVC 测试:在我的测试用例中,我传递了一个无效Bar
对象(年龄为零)。被MethodArgumentNotValidException
抛出,但它嵌套在NestedServletException
. 无论如何MethodArgumentNotValidException
通过现有/自定义从控制器抛出异常HandlerExceptionResolver
,以便我当前的测试用例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>