[英]MockMvc on spring mvc controller
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 而我的MyControllerTest类中的以下代码
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 MyFormBean中的id字段用@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. 因此,我尝试了各种排列方式(requestAttr,sessionAttr等,而不是param等),但我无法使其正常工作。 At best I get exceptions on the @Valid clause.
充其量我在@Valid子句上会获得异常。 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. 任何帮助表示赞赏,谢谢。
问题不在您的测试中,问题出在您的主代码(控制器)上,因为url路径仅映射到使用@PathVariable
注释的参数, @PathVariable
映射到表单对象!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.