0

I have the following code in my controller:

@Controller
@RequestMapping(value="/my")
public class MyController  {

    @RequestMapping(value="/zone/{id}", method=RequestMethod.POST)
    public ModelAndView zone(@PathVariable Long id, @Valid MyFormBean formBean){

    System.out.println(formBean.getId());
    ModelMap mod = new ModelMap();
    mod.put("test", true);
    return new ModelAndView(myViewName, model);
    }
}

And the following code in my MyControllerTest class

public class MyControllerTest {
  @InjectMocks
  private MyController myController = new MyController();

  private MockMvc mockMvc = MockMvcBuilders.standaloneSetup(MyController).build();

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void myTest() {
     MyFormBean formBean = new MyFormBean();
     formBean.setId(5L);
     ModelAndView mav = new ModelAndView();

     int id = 10;

     try {
       MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/my/zone/" + id).param("formData", formData.toString())).andReturn();
     } catch(Exception e) {
       fail(e.getMessage());
     }
}

The id field in MyFormBean is annotated with @NotNull

So I tried various permutations of this (requestAttr, sessionAttr, etc. instead of param, and a few others) and I cannot get it to work. At best I get exceptions on the @Valid clause. Other times the test will pass without actually entering the method.

I have tried to follow a few examples but can't find anything with my specific method signature.

Any help appreciated, thanks.

Dax Durax
  • 1,607
  • 5
  • 23
  • 31
  • It seams that I understand your problem in the wrong way. Could you elaborate "I cannot get it to work." please? – Ralph Jul 14 '14 at 17:52

1 Answers1

0

The problem is not in your test, the problem is your main code (controller), because the url path is only mapped to the parameter annotated with @PathVariable, but NOT into the form-object!

Ralph
  • 118,862
  • 56
  • 287
  • 383
  • Could you elaborate please? The controller method functions as expected as is, is it necessary to add the form-object to the requestmapping? – Dax Durax Jul 14 '14 at 13:54