简体   繁体   English

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

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

Using Mockito使用 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我们有这种类型的服务,可以从 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);
    }
}

When using Mockito we want to use this service (the real service) and not mock it so we use:当使用 Mockito 时,我们想使用这个服务(真正的服务)而不是模拟它,所以我们使用:

 @Spy
    private EmailValidationService emailValidationService = new EmailValidationService();

But the "regexPattern" variable always gets null value and not the default value但是“regexPattern”变量总是得到 null 值而不是默认值

Any ideas?有任何想法吗?

Use @SpyBean instead of a @Spy in your test:在测试中使用@SpyBean而不是@Spy

@SpyBean
private EmailValidationService emailValidationService;

For this you'll need a spring-boot-test dependency and make sure your test is run with Spring runner:为此,您需要一个spring-boot-test依赖项,并确保您的测试使用 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.如果您使用的是 JUnit 4,请不要忘记也将 @RunWith(SpringRunner.class) 添加到您的测试中,否则注释将被忽略。 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.如果您使用的是 JUnit 5,则无需将等效的 @ExtendWith(SpringExtension.class) 添加为 @SpringBootTest 并且其他 @...Test 注释已使用它进行注释。

Another alternative is to explicitly set the field value in your Spy:另一种选择是在 Spy 中显式设置字段值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM