注册控制器不允许通过以下方式发送帐户 ID 字段:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setDisallowedFields("id");
binder.setRequiredFields("username","password","emailAddress");
}
@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT })
public String handleRegistration(@ModelAttribute Account account, BindingResult result) {
if (result.hasErrors()) {
return "customer/register";
}
我运行以下测试以确保不允许使用 ID:
@Test
public void testPutRequestWithIdPassedRegistrationController() throws Exception {
this.mockMvc.perform(post("/customer/register")
.param("id", "1")
.param("username", "shouldBeIgnored")
.param("password", "123")
.param("emailAddress", "testIgnored@gmail.com")
.param("address.country", "RU")
.param("address.city", "Nsk")
.param("address.street", "Lenin"))
.andExpect(model().hasErrors())
.andExpect(view().name("customer/register"));
}
但测试失败原因:java.lang.AssertionError: Expected binding/validation errors
这里的比较是尝试在不通过不可为空的字段的情况下创建帐户的测试并且它通过了很好,这意味着setRequiredFields
工作正常:
@Test
public void testPutRequestWithoutNeededFieldsRegistrationController() throws Exception {
this.mockMvc.perform(post("/customer/register"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("customer/register"))
.andExpect(model().hasErrors())
.andExpect(model().errorCount(3));
}
为什么它会以这种方式工作?我如何确定不允许使用该 id?