I am using spring MVC testing: In my test case, I am passing an invalid Bar
object(age with zero). The MethodArgumentNotValidException
is being thrown, but it is nested inside a NestedServletException
. Is there anyway to throw the MethodArgumentNotValidException
exception from the controller through an existing/custom HandlerExceptionResolver
, so that my current test case checkHit2
passes?
Controller:
@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)));
Bar
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 output
java.lang.Exception: Unexpected exception,
expected<org.springframework.web.bind.MethodArgumentNotValidException> but
was<org.springframework.web.util.NestedServletException>