spring-bootmockitospy

Is the a way to @autowire the real service with Mockito and still get @Value properties


Using Mockito

We have this type of service that get the "regexPattern" value from application.yml or gets the default value if it is not defined

@Service
@Log4j2
public class EmailValidationService {

    @Value("${validators.emailValidator.regexPattern:'"+ DefaultEmailValidator.DEFAULT_PATTERN  + "'}")
    private String regexPattern;

    public EmailValidator getEmailValidator(){
        return new DefaultEmailValidator(regexPattern);
    }
}

When using Mockito we want to use this service (the real service) and not mock it so we use:

 @Spy
    private EmailValidationService emailValidationService = new EmailValidationService();

But the "regexPattern" variable always gets null value and not the default value

Any ideas?


Solution

  • Use @SpyBean instead of a @Spy in your test:

    @SpyBean
    private EmailValidationService emailValidationService;
    

    For this you'll need a spring-boot-test dependency and make sure your test is run with Spring runner:

    If you are using JUnit 4, do not forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there is no need to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the other @…​Test annotations are already annotated with it.

    Another alternative is to explicitly set the field value in your Spy:

    ReflectionTestUtils.setField(emailValidationService, "regexPattern", DefaultEmailValidator.DEFAULT_PATTERN);