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

14,912

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();
}
Share:
14,912
Whimusical
Author by

Whimusical

Half of the time we're gone but we don't know where...

Updated on June 14, 2022

Comments

  • Whimusical
    Whimusical almost 2 years

    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:

    • Why does Mockito call @PostConstruct?
    • How can I disable @PostConstruct for mocking?

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

  • Whimusical
    Whimusical about 7 years
    You seem to be right. It's Spring!! But it's called after the return of the instance in @Configuration's @Bean method. How can I disable it?
  • john16384
    john16384 about 7 years
    I donot think you can. Unless you are writing an integration test for multiple components, you're better off using mocks for unit testing.