为什么@Constraints注释不能用于我的测试?

时间:2016-11-05 10:04:29

标签: java playframework annotations playframework-2.0 ebean

我已创建此User课程:

@Entity
public class User extends Model {

    @Id
    @Constraints.Email
    public String email;

    @Constraints.MinLength(3)
    @Constraints.MaxLength(255)
    public String firstName;

    @Constraints.MinLength(3)
    @Constraints.MaxLength(255)
    public String lastName;

    @Constraints.MinLength(3)
    @Constraints.MaxLength(255)
    public String username;

    @Constraints.MinLength(16)
    @Constraints.MaxLength(255)
    public String password;

    public static Finder<String, User> finder = new Finder<>(User.class);

    public static User create(User user){
        user.password = BCrypt.hashpw(user.password, BCrypt.gensalt(12));
        user.save();
        return user;
        }
     ...
}

我注意到我可以保存 User。这意味着,如果没有email,则此用户将保留在我的数据库中。

    @Test
    public void createEmptyUser(){
        User user = new User();
        user.email="";
        user.save();

        assertTrue(user.email.isEmpty());
        assertNotNull(User.finder.byId(user.email));
        assertEquals(true, User.findByEmail(user.email).isPresent());
    }

为什么我的考试通过?

1 个答案:

答案 0 :(得分:0)

正如我在此处https://github.com/playframework/playframework/blob/master/framework/src/play-java-forms/src/main/java/play/data/validation/Constraints.java所见,isValid类的EmailValidator方法如果其agrument为空字符串则返回true:

public static class EmailValidator extends Validator<String> implements ConstraintValidator<Email, String> {

        public boolean isValid(String object) {

            if(object == null || object.length() == 0) {
                return true;
            }

            return regex.matcher(object).matches();
        }
}

考虑将@Constraints.Required@Formats.NonEmpty添加到此验证中。此外,您可以看到MinLengthMaxLength验证程序的行为方式相同。