首页 > 解决方案 > Springboot ConstraintValidator not reading configurationProperties with MockitoJUnitRunner or SpringBoot

问题描述

I have written a ConstraintValidator which will read keyvalue pair from yaml file. Th code works fine during runtime but not working while testing. I tried with both MockitoJUnitRunner and SpringRunner classes.

I have used the same logic in CustomConverters implementation which is able to read the keyvalue pair during runtime and testing.

Could you please advise how to test ConstraintValidator with configurationproperties.

Code:

 @ConfigurationProperties(prefix="gender")
    public class GenderValidator implements ConstraintValidator<Gender, String> {

    private Map<String, String> type = new HashMap<String, String>();

    @Override
    public void initialize(Gender gender) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext ctx) {      
        return getType().containsKey(value);
    }
    public Map<String, String> getType() {return type; }   
    }

Configuration

 gender:
    type:
      M: male
      F: female

TestCode:

 Set<ConstraintViolation<GenderDetails>> constraintViolations =
                validator.validate(payload);
        assertThat (constraintViolations.isEmpty(), is(true) );

AssertThat always returns error.

Note: I have configured the PropertySourcesPlaceholderConfigurer under configuration class which is working fine when I test the CustomConverter.

Thanks for your help.`

标签: spring-bootenumsmockitoconstraintsspring-boot-test

解决方案


推荐阅读