问题描述
我正在使用 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;
/* ... */
}
现在我还想将 real 对象注入私有 @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
注释的字段作为潜在的候选注入到使用 @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 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!