How to test validation annotations of a class using JUnit?

后端 未结 9 1123
盖世英雄少女心
盖世英雄少女心 2020-12-07 17:29

I need to test the validation annotations but it looks like they do not work. I am not sure if the JUnit is also correct. Currently, the test will be passed but as you can s

9条回答
  •  春和景丽
    2020-12-07 18:14

    The annotations do not do anything by themselves, you need to use a Validator to process the object.

    Your test needs to run some code like this

        Configuration configuration = Validation
            .byDefaultProvider()
            .providerResolver( new MyResolverStrategy() ) // <== this is where is gets tricky
            .configure();
        ValidatorFactory factory = configuration.buildValidatorFactory();
    
        Contact contact = new Contact();
        contact.setEmail("Jackyahoo.com");
        contact.setName("Jack");
        factory.getValidator().validate(contact); <== this normally gets run in the background by whatever framework you are using
    

    However, the difficulty you face here are these are all interfaces, you will need implementations to be able to test. You could implement it yourself or find one to use.

    However the question you want to ask yourself is what are you trying to test? That the hibernate validator works the way it should? or that your regex is correct?

    If this was me I would assume that the Validator works(ie someone else tested that) and focus on the regex. Which would involve a bit of reflection

    public void emailRegex(String email,boolean validates){
    
        Field field = Contact.class.getDeclaredField("email");
        javax.validation.constraints.Pattern[] annotations = field.getAnnotationsByType(javax.validation.constraints.Pattern.class);
        assertEquals(email.matches(annotations[0].regexp()),validates);
    
    }
    

    then you can define your testMethods which are actual unit tests

    @Test
    public void testInvalidEmail() throws NoSuchFieldException {
        emailRegex("Jackyahoo.com", false);
    }
    
    @Test
    public void testValidEmail() throws NoSuchFieldException {
        emailRegex("jack@yahoo.com", true);
    }
    
    @Test
    public void testNoUpperCase() throws NoSuchFieldException {
        emailRegex("Jack@yahoo.com", false);
    }
    

提交回复
热议问题