How to test validation annotations of a class using JUnit?

后端 未结 9 1161
盖世英雄少女心
盖世英雄少女心 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:11

    import javax.validation.ConstraintViolation;
    import javax.validation.Validation;
    import javax.validation.Validator;
    import javax.validation.ValidatorFactory;
    import static org.junit.Assert.assertFalse;
    import static org.junit.Assert.assertTrue;
    import org.junit.Before;
    import org.junit.Test;
    
    public class ValidationTest {
    
        private Validator validator;
    
        @Before
        public void init() {
    
            ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
            this.validator = vf.getValidator();
    
        }
    
        @Test
        public void prereqsMet() {
            Workshop validWorkshop = new Workshop(2, 2, true, 3);
            Set> violations = this.validator.validate(validWorkshop);
            assertTrue(violations.isEmpty());
        }  
    }
    

    Strictly speaking it is not a unit test, rather an Integration Test. In Unit Test you would like to test the validator logic only, without any dependencies to the SPI.

    https://www.adam-bien.com/roller/abien/entry/unit_integration_testing_the_bean

提交回复
热议问题