問題描述
我有這樣的設置:
Bean類:
private final Map<String, String> configCache = new HashMap<>();
@PostConstruct
private void fillCache() { (...) configCache.clear();}
TestConfig 類:
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
@Primary
public Bean beanMock() {
return Mockito.mock(Bean.class);
}
Test 類:哪個 @Autowires
bean.
Test class: which @Autowires
the bean.
似乎當 Mockito 在 TestConfig 中創建模擬時,它調用了 @PostConstruct ,而 @PostConstruct 又似乎在映射字段初始化之前被調用,因此它引發了異常.
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 調用 @PostConstruct?
- 如何禁用 @PostConstruct 進行模擬?
顯然調用是在 Spring 從 Config 的 @Bean 方法中重新調用 bean 之前的實例化之后完成的
Apparently the call is done after the instantiation just before Spring retrns the bean from a Config's @Bean method
推薦答案
Mockito 沒有調用 @PostConstruct
-- Spring 是.你說在你的測試中你使用了 @Autowired
,這不是一個 Mockito 注釋.
Mockito isn't calling @PostConstruct
-- Spring is. You say that in your test you use @Autowired
, which is not a Mockito annotation.
如果您打算使用 @Mock
,您會發現 Mockito 不會調用您的 @PostConstruct
方法.
If you meant to use @Mock
, you'll find that Mockito won't call your @PostConstruct
method.
換句話說,像這樣編寫你的測試類:
In other words, write your test class like this:
@Mock Bean myBean;
@Before
public void before() {
MockitoAnnotations.initMocks();
}
這篇關于Mockito + Spring + @PostConstruct,mock初始化錯誤,為什么會調用@PostConstruct?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!