lundi 30 mars 2020

Spring Controller Test using actual data during bean validation

I have a controller method for creating a user like below.

@Secured({RoleNames.ADMIN})
@PostMapping(value = "/users/create")
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserCommand command) {
    UserDto userDto = userService.create(command);
    return ResponseEntity.ok().body(userDto);
}

I need to validate CreateUserCommand (with holds form data come from front-end). For example whether email already exists in database.

I created a validator like below:

public class UserEmailExistsValidator implements ConstraintValidator {

@Autowired
private UserService userService;

public UserEmailExistsValidator(UserService userService) {
    this.userService = userService;
}

@Override
public boolean isValid(CreateUserCommand command, ConstraintValidatorContext constraintValidatorContext) {
    UserDto userDto = userService.getByEmail(command.getEmail());
    return userDto == null;
}

}

My problem is that: when I try to run Controller Test for this "users/create" endpoint, it checks actual database (not test database) whether e-mail exists that user. So if that user e-mail exists in database, validations fail and therefore tests are failing.

I am using Spring Boot 2.1.8, Mockito3.0.0.

Aucun commentaire:

Enregistrer un commentaire