java Mockito + Spring + @PostConstruct,mock 初始化错误,为什么会调用@PostConstruct?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42112625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito + Spring + @PostConstruct, mock initialization error, why is @PostConstruct called?
提问by Whimusical
I have a set up like:
我有一个类似的设置:
Beanclass:
豆类:
private final Map<String, String> configCache = new HashMap<>();
@PostConstruct
private void fillCache() { (...) configCache.clear();}
TestConfigclass:
测试配置类:
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
@Primary
public Bean beanMock() {
return Mockito.mock(Bean.class);
}
Testclass: which @Autowires
the bean.
测试类:其中@Autowires
的bean。
It seems when Mockito is creating the mock in TestConfig, it calls @PostConstruct which in turn seems to be called before the map field is initialized so it throws an exception.
似乎当 Mockito 在 TestConfig 中创建模拟时,它调用 @PostConstruct 似乎在初始化 map 字段之前调用它,因此它抛出异常。
My question is:
我的问题是:
- Why does Mockito call @PostConstruct?
- How can I disable @PostConstruct for mocking?
- 为什么 Mockito 调用@PostConstruct?
- 如何禁用@PostConstruct 进行模拟?
EDIT: Apparently the call is done after the instantiation just before Spring retrns the bean from a Config's @Bean method
编辑:显然调用是在 Spring 从 Config 的 @Bean 方法中重新获取 bean 之前的实例化之后完成的
采纳答案by john16384
Mockito isn't calling @PostConstruct
-- Spring is. You say that in your test you use @Autowired
, which is not a Mockito annotation.
Mockito 不是在调用——Spring@PostConstruct
是。您说在您的测试中使用了@Autowired
,这不是 Mockito 注释。
If you meant to use @Mock
, you'll find that Mockito won't call your @PostConstruct
method.
如果您打算使用@Mock
,您会发现 Mockito 不会调用您的@PostConstruct
方法。
In other words, write your test class like this:
换句话说,像这样编写你的测试类:
@Mock Bean myBean;
@Before
public void before() {
MockitoAnnotations.initMocks();
}