I need to mock the @ModelAttribute
in the request handler of spring controller. I hope to pass diverse values via mock instead of passsing it via MockMVC request parameter. There is a request interceptor which works and possibly is nullyfying even the model object attribute is paased via request parameter hence this question.
So below is the partial code snippet; Componet1: Controller whose request handler's @ModelAtrribute is to be mocked.
@Controller public class MyController { /** some code here*/
@RequestMapping(path = "/myRequest", method = RequestMethod.POST)
@ResponseBody
public String requestHanderForMyRequest(HttpServletRequest request, @ModelAttribute(name="myBean") People person) {
...
Date birthDate = person.getBirthDate();
...
// do something with date
/** prepare JSON response and return */
return "{ ...}";
}
}
Component 2: DateFieldInterceptor.java Intercepts date field in request and processes it and then updates it if success flow otherwise resets to null.
Component 3: Mock test method in JUnit test class
@Test
public void testRequestHanderForMyRequest() {
try {
ResponseInstance responseInstance = testUtility .loadResponseFromFile("testFile.json");
Assert.assertNotNull("No base data", responseInstance);
MvcResult resultantMvc = mockMvc.perform(post("/myRequest")
.session(mockHttpSession)
.param(START_DATE, START_DATE_VALUE)
.param("birthdate", BIRTH_DATE_VALUE)
.param("personName", "dfs edfsd")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$").exists())
.andExpect(jsonPath("$").isNotEmpty())
.andExpect(jsonPath("$", Matchers.hasKey(PAYLOAD)))
.andExpect(jsonPath("$.*", Matchers.hasSize(1)))
.andExpect(jsonPath(JSON_PATH_ROOT_PAYLOAD).isArray())
.andExpect(jsonPath(JSON_PATH_ROOT_PAYLOAD).isNotEmpty())
.andReturn();
Assert.assertNotNull(MVC_RESULT_IS_MISSING_FOR_THE_REQUEST, resultantMvc);
String payloadData = resultantMvc.getResponse().getContentAsString();
Assert.assertTrue(RESPONSE_IS_MISSING_PAYLOAD_DATA, StringUtils.isNotBlank(payloadData));
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
The date interceptor is somehow going to negative flow and resetting the date field to null. I wish to unit test the birthdate field of People instance. If I can somehow mock the person.getBirthDate() then I should be alright with the unit test. But mocks don't seem to work for @ModelAttribute parameters.