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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:22:30  来源:igfitidea点击:

Mockito + Spring + @PostConstruct, mock initialization error, why is @PostConstruct called?

javaspringunit-testingspring-bootmockito

提问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 @Autowiresthe 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 @PostConstructmethod.

如果您打算使用@Mock,您会发现 Mockito 不会调用您的@PostConstruct方法。

In other words, write your test class like this:

换句话说,像这样编写你的测试类:

@Mock Bean myBean;

@Before
public void before() {
    MockitoAnnotations.initMocks();
}