Whimusical
Whimusical

Reputation: 6649

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

I have a set up like:

Bean class:

private final Map<String, String> configCache = new HashMap<>();
@PostConstruct
private void fillCache() {  (...) configCache.clear();} 

TestConfig class:

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
@Primary
public Bean beanMock() {
    return Mockito.mock(Bean.class);
}

Test class: which @Autowires the 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.

My question is:

EDIT: Apparently the call is done after the instantiation just before Spring retrns the bean from a Config's @Bean method

Upvotes: 5

Views: 18385

Answers (1)

john16384
john16384

Reputation: 8064

Mockito isn't calling @PostConstruct -- Spring is. You say that in your test you use @Autowired, which is not a Mockito annotation.

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();
}

Upvotes: 4

Related Questions