hi to everyone here,
I am facing a roadblock in my mvc mock testing and I am hoping someone can provide me with some assistance.
I am trying to perform a mock http POST with parameters. However, the .param() method can only accept String values.
Here's the implementation of somemethod()Code:String a = "a"; int b = 10; this.mockMvc .perform( post("/service/somemethod") .param("a", a) .param("b", b) // flags as error );
To make the test class compile, I had to make variable b into a String and change the method argument of int b to String b.Code:@ModelAttribute(value = "response") @RequestMapping(value = "/somemethod", method = RequestMethod.POST) public MyResponse somemethod(@RequestParam String a, @RequestParam int b) { return new MyResponse(); }
So I dig further into MockHttpServletRequestBuilder.param():Code:@ModelAttribute(value = "response") @RequestMapping(value = "/somemethod", method = RequestMethod.POST) public MyResponse somemethod(@RequestParam String a, @RequestParam String b) { return new MyResponse(); }
Upon inspecting the code in MockHttpServletRequestBuilder, I conclude it's not possible to use param with a non-String parameter. Also, it does not make sense to have a generic type method addToMultiValueMap and yet only accept String values. If that's the case, why bother having a generic type return for addToMultiValueMap?Code:private final MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); ... ... /** * Add a request parameter to the {@link MockHttpServletRequest}. * If called more than once, the new values are added. * * @param name the parameter name * @param values one or more values */ public MockHttpServletRequestBuilder param(String name, String... values) { addToMultiValueMap(this.parameters, name, values); return this; } ... ... private static <T> void addToMultiValueMap(MultiValueMap<String, T> map, String name, T[] values) { Assert.hasLength(name, "'name' must not be empty"); Assert.notNull(values, "'values' is required"); Assert.notEmpty(values, "'values' must not be empty"); for (T value : values) { map.add(name, value); } }
I don't want to change somemethod() argument b to String just because param() can't accept non-Strings. Is there any other way I can use mockMvc to post non-Strings?
I am using 3.2.0.RELEASE.
Thanks.


Reply With Quote
