Mockito + Spring + @PostConstruct, mock initialization error, why is @PostConstruct called?(Mockito + Spring + @PostConstruct,mock初始化错误,为什么会调用@PostConstruct?)
问题描述
我有这样的设置:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mockito + Spring + @PostConstruct,mock初始化错误,为什么会调用@PostConstruct?


基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01