2
我使用的是Spring MVC测试:在我的测试用例中,我传递了一个无效的Bar
对象(年龄为零)。 MethodArgumentNotValidException
正在抛出,但它嵌套在NestedServletException
内。无论如何抛出MethodArgumentNotValidException
异常从控制器通过现有/自定义HandlerExceptionResolver
,以便我目前的测试案例checkHit2
通过?在Junit测试用例中处理MethodArgumentNotValidException?
控制器:
@RequestMapping(value="/test", method = RequestMethod.POST, headers="Accept=application/json")
@ResponseBody
public Bar getTables(@Valid @RequestBody Bar id) {
return id;
}
的TestCase
@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>
结帐的'ExpectedException'规则,写自己的衍生物为您包装的异常? – 2014-02-07 06:45:53
这意味着我弯曲我的测试用例来接受'NestedServletException'。我想要的是以某种方式改变控制器的行为,直接抛出'MethodArgumentNotValidException',而不是将它嵌套在'NestedServletException'中 – jacquard