本文介绍了Mockito:将真实对象注入私有的@Autowired字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mockito的 @Mock @InjectMocks 注释将依赖项注入私有字段,这些字段已注明Spring的 @Autowired

I'm using Mockito's @Mock and @InjectMocks annotations to inject dependencies into private fields which are annotated with Spring's @Autowired:

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Mock
    private SomeService service;

    @InjectMocks
    private Demo demo;

    /* ... */
}

public class Demo {

    @Autowired
    private SomeService service;

    /* ... */
}

现在我还想将真正的对象注入私有 @Autowired 字段(没有setter)。这是可能的还是机制仅限于注入Mocks?

Now I would like to also inject real objects into private @Autowired fields (without setters). Is this possible or is the mechanism limited to injecting Mocks only?

推荐答案

使用 @Spy 注释

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Spy
    private SomeService service = new RealServiceImpl();

    @InjectMocks
    private Demo demo;

    /* ... */
}

Mockito将考虑具有 @Mock @Spy 注释的所有字段作为注入<$注释的实例的潜在候选者c $ c> @InjectMocks 注释。在上面的例子中,'RealServiceImpl'实例将被注入'demo'

Mockito will consider all fields having @Mock or @Spy annotation as potential candidates to be injected into the instance annotated with @InjectMocks annotation. In the above case 'RealServiceImpl' instance will get injected into the 'demo'

有关详细信息,请参阅

这篇关于Mockito:将真实对象注入私有的@Autowired字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:04