Writing JUnit tests for Spring Validator implementation

后端 未结 2 800
小蘑菇
小蘑菇 2020-12-08 20:09

I\'m using Spring Validator implementations to validate my object and I would like to know how do you write a unit test for a validator like this one:

public         


        
2条回答
  •  生来不讨喜
    2020-12-08 20:54

    It is a really straight forward test without any mock. (just the error-object creation is a bit tricky)

    @Test
    public void testValidationWithValidAddress() {
        AdressValidator addressValidator = new AddressValidator();
        CustomValidator validatorUnderTest = new CustomValidator(adressValidator);
    
        Address validAddress = new Address();
        validAddress.set... everything to make it valid
    
        Errors errors = new BeanPropertyBindingResult(validAddress, "validAddress");
        validatorUnderTest.validate(validAddress, errors);
    
        assertFalse(errors.hasErrors()); 
    }
    
    
    @Test
    public void testValidationWithEmptyFirstNameAddress() {
        AdressValidator addressValidator = new AddressValidator();
        CustomValidator validatorUnderTest = new CustomValidator(adressValidator);
    
        Address validAddress = new Address();
        invalidAddress.setFirstName("")
        invalidAddress.set... everything to make it valid exept the first name
    
        Errors errors = new BeanPropertyBindingResult(invalidAddress, "invalidAddress");
        validatorUnderTest.validate(invalidAddress, errors);
    
        assertTrue(errors.hasErrors());
        assertNotNull(errors.getFieldError("firstName"));
    }
    

    BTW: if you really want to make it more complicate and make it complicate by a mock, then have a look at this Blog, they use a two mocks, one for the object to test (ok, this is useful if you can not create one), and a second for the Error object (I think this is more complicated the it must be.)

提交回复
热议问题