Mockito + Spring + @PostConstruct,模拟初始化错误,为什么调用@PostConstruct? [英] Mockito + Spring + @PostConstruct, mock initialization error, why is @PostConstruct called?

查看:932
本文介绍了Mockito + Spring + @PostConstruct,模拟初始化错误,为什么调用@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.

当Mockito在TestConfig中创建模拟时,它会调用@PostConstruct,而后者似乎在初始化map字段之前被调用,从而引发异常.

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,模拟初始化错误,为什么调用@PostConstruct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆