Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Test - Validator: Invalid target for Validator

I'm getting the following error when I'm trying to run a test:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Invalid target for Validator [userCreateFormValidator bean]: com.ar.empresa.forms.UserCreateForm@15c3585

Caused by: java.lang.IllegalStateException: Invalid target for Validator [userCreateFormValidator bean]: com.ar.empresa.forms.UserCreateForm@15c3585 at org.springframework.validation.DataBinder.assertValidators(DataBinder.java:567) at org.springframework.validation.DataBinder.addValidators(DataBinder.java:578) at com.ar.empresa.controllers.UserController.initBinder(UserController.java:36) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498)

The code is:

Controller:

@Controller
public class UserController {
private UserService userService;
private UserCreateFormValidator userCreateFormValidator;

@Autowired
public UserController(UserService userService, UserCreateFormValidator userCreateFormValidator) {
    this.userService = userService;
    this.userCreateFormValidator = userCreateFormValidator;
}

@InitBinder("form")
public void initBinder(WebDataBinder binder) {
    binder.addValidators(userCreateFormValidator);
}

@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(value = "/user/create", method = RequestMethod.GET)
public ModelAndView getUserCreatePage() {
    return new ModelAndView("user_create", "form", new UserCreateForm());
}

@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(value = "/user/create", method = RequestMethod.POST)
public String handleUserCreateForm(@Valid @ModelAttribute("form") UserCreateForm form, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "user_create";
    }
    try {
        userService.create(form);
    } catch (DataIntegrityViolationException e) {
        bindingResult.reject("email.exists", "Email already exists");
        return "user_create";
    }
    return "redirect:/users";
}
}

Validator:

@Component
public class UserCreateFormValidator implements Validator {

private final UserService userService;

@Autowired
public UserCreateFormValidator(UserService userService) {
    this.userService = userService;
}

@Override
public boolean supports(Class<?> clazz) {
    return clazz.equals(UserCreateForm.class);
}

@Override
public void validate(Object target, Errors errors) {
    UserCreateForm form = (UserCreateForm) target;
    validatePasswords(errors, form);
    validateEmail(errors, form);
}

private void validatePasswords(Errors errors, UserCreateForm form) {
    if (!form.getPassword().equals(form.getPasswordRepeated())) {
        errors.reject("password.no_match", "Passwords do not match");
    }
}

private void validateEmail(Errors errors, UserCreateForm form) {
    if (userService.getUserByEmail(form.getEmail()).isPresent()) {
        errors.reject("email.exists", "User with this email already exists");
    }
}
}

UserCreateForm:

public class UserCreateForm {

@NotEmpty
private String email = "";

@NotEmpty
private String password = "";

@NotEmpty
private String passwordRepeated = "";

@NotNull
private Role role = Role.USER;

public String getEmail() {
    return email;
}

public String getPassword() {
    return password;
}

public String getPasswordRepeated() {
    return passwordRepeated;
}

public Role getRole() {
    return role;
}

public void setEmail(String email) {
    this.email = email;
}

public void setPassword(String password) {
    this.password = password;
}

public void setPasswordRepeated(String passwordRepeated) {
    this.passwordRepeated = passwordRepeated;
}

public void setRole(Role role) {
    this.role = role;
}
}

Test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {

private MockMvc mockMvc;

private MediaType contentType = new MediaType(APPLICATION_JSON.getType(),
        APPLICATION_JSON.getSubtype(),
        Charset.forName("utf8"));

@MockBean
private UserService userService;

@MockBean
private UserCreateFormValidator userCreateFormValidator;

@Autowired
FilterChainProxy springSecurityFilterChain;

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(new UserController(userService,userCreateFormValidator)).apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain)).build();
}

@Test
@WithMockUser(username="user",
        password="password",
        roles="ADMIN")
public void homePage_authenticatedUser() throws Exception {
    mockMvc.perform(get("/user/create"))
            .andExpect(status().isOk())
            .andExpect(view().name("user_create"));
}
}

I don't know why, because it is a GET method, so it don't have to validate it. Thanks! :)

like image 252
AleGallagher Avatar asked Mar 05 '17 15:03

AleGallagher


2 Answers

You got this exception because you didn't mock the behaviour of public boolean supports(Class<?> clazz) method on your userCreateFormValidator @Mockbean. If you take a look at the code of org.springframework.validation.DataBinder.assertValidators(DataBinder.java) from the log you posted, you can find there how the validators are processed and how java.lang.IllegalStateException is thrown. In Spring 4.3.8, it looks like this

if(validator != null && this.getTarget() != null && !validator.supports(this.getTarget().getClass())) {
    throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + this.getTarget());
}

You didn't mock supports method of the validator and returns false by default, causing Spring code above throw the IllegalStateException.

TLDR, just give me solution:

You have to mock supports method on your validator. Add following to @Before or @BeforeClass method.

when(requestValidatorMock.supports(any())).thenReturn(true);
like image 63
Patrik Stas Avatar answered Nov 15 '22 04:11

Patrik Stas


I cant comment on the correct answer but his solution worked:

Here is what I had to do for this exact error.

//Imports
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;


    @MockBean
    ApiValidationRouter apiValidationRouter;

    @Before
    public void beforeClass() throws Exception {
        when(apiValidationRouter.supports(any())).thenReturn(true);
    }

like image 35
Braden Borman Avatar answered Nov 15 '22 03:11

Braden Borman