2013-11-16 4 views
2

регистрационном контроллер disallowes отправки поля идентификатора аккаунта следующий:Spring setDisallowedFields не работает

@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", "[email protected]") 
      .param("address.country", "RU") 
      .param("address.city", "Nsk") 
      .param("address.street", "Lenin")) 
      .andExpect(model().hasErrors()) 
      .andExpect(view().name("customer/register")); 
} 

Но тест не пройден причина: java.lang.AssertionError: Ожидаемые ошибки привязки/проверки

Для сравнения здесь приведен тест, который пытается создать учетную запись без прохождения не-NULLABLE поля и она проходит хорошо, это означает, что 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 не разрешен?

ответ

2

Spring не рассматривает недопустимые поля как ошибки. Он просто хранит их как suppressedFields в BindException. Во время отладки я мог получить доступ к нему с помощью:

((BindingResult)getModelAndView(result).getModelMap().get("org.springframework.validation.BindingResult.account")).getSuppressedFields() 

При вызове из метода hasErrors().

Так, чтобы убедиться, что идентификатор не используется, я просто передал его через Params, а затем проверить, что аккаунт с таким именем (это уникальное поле) имеет другое значение ID:

String notExistingId = "999"; 
String newUserName = "newUser"; 
this.mockMvc.perform(post("/customer/register") 
     .param("id", notExistingId) 
     .param("username", newUserName) 
     .param("password", "123") 
     .param("emailAddress", "[email protected]") 
     .param("address.country", "RU") 
     .param("address.city", "Nsk") 
     .param("address.street", "Lenin")) 
     .andExpect(model().hasNoErrors()) 
     .andExpect(view().name("redirect:/index.htm")); 
Optional<Account> account = accountService.getAccount(newUserName); 
assertTrue("Account with the username should exist", account.isPresent()); 
assertNotSame("Account id should not be equal to the id we try to pass with parameters", 
     Long.parseLong(notExistingId), 
     account.get().getId()); 
Смежные вопросы