是使用 Mockito @autowire 真正的服务并仍然获得 @Value 属性的方法吗

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

使用 Mockito

我们有这种类型的服务,可以从 application.yml 获取“regexPattern”值,如果未定义则获取默认值

@Service
@Log4j2
public class EmailValidationService {

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

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

在使用 Mockito 时,我们希望使用此服务(真正的服务)而不是模拟它 所以我们使用:

 @Spy
    private EmailValidationService emailValidationService = new EmailValidationService();

但是“regexPattern”变量总是得到空值而不是默认值

有什么想法吗?

在测试中使用 @SpyBean 而不是 @Spy

@SpyBean
private EmailValidationService emailValidationService;

为此你需要一个 spring-boot-test 依赖项并确保你的测试是 运行 with Spring 运行ner:

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.

另一种方法是在 Spy 中显式设置字段值:

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