0

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
VinayakC
  • 21
  • 3
  • 1
    try to add your test code – Maciej Kowalski Jan 11 '18 at 13:31
  • @MaciejKowalski, Thanks for you input. I have added seudo code. – VinayakC Jan 11 '18 at 14:51
  • how do you create the mockMvc object? – Maciej Kowalski Jan 11 '18 at 15:10
  • @MaciejKowalski, I have autowired MockMvc. – VinayakC Jan 11 '18 at 15:25
  • 1
    I am now able to bypass this issue. Using [flash][1] attribute the value of date attribute is retained. I added my testModelObject as .flashAttribute("myBean", testModelObject) in the mockMVc instance in my unit test method. See comments in following example [Example][2] . I am still looking for effective way to mock @ModelAttribute though. [1]: https://docs.spring.io/autorepo/docs/spring-framework/3.1.0.RC1/reference/htmlsingle/#d0e1595 [2]: https://stackoverflow.com/questions/19274105/how-to-test-that-method-has-added-redirectattributes-by-mockmvc – VinayakC Jan 14 '18 at 06:27

0 Answers0