[英]Mockito + Spring + @PostConstruct, mock initialization error, why is @PostConstruct called?
I have a set up like: 我有一个像这样的设置:
Bean class: Bean类:
private final Map<String, String> configCache = new HashMap<>();
@PostConstruct
private void fillCache() { (...) configCache.clear();}
TestConfig class: TestConfig类:
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
@Primary
public Bean beanMock() {
return Mockito.mock(Bean.class);
}
Test class: 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: 我的问题是:
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之前
Mockito isn't calling @PostConstruct
-- Spring is. 是的Mockito不调用
@PostConstruct
-春天。 You say that in your test you use @Autowired
, which is not a Mockito annotation. 您说在测试中使用
@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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.