@PostConstruct not called when using Mockito @Spy annotation

annotations, java, mockito, spring

Solution

No, there isn't. PostConstruct is a Spring concept. But nothing forbids you to call it in your setup method:

@Before
public void prepare() {
    MockitoAnnotations.initMocks(this);
    this.b.postConstruct();
}

Problem

I am using Spring, TestNG and Mockito frameworks. I am writing a unit test for a class A that has a dependency on class B. Class B has a method annotated with `@PostConstruct`. While writing Unit test case using TestNG for class A, I am annotating an instance of class B with Mockito `@Spy` in the test class. I can see the instance of B being created properly by Mockito. But why `@PostConstruct` code is not called when Mockito is processing `@Spy` annotation? So, what I have done is I moved the code inside `@PostConstruct` to the constructor. Is there any way to make Mockito execute any 'Post-processing' method while processing `@Spy` annotation? Appreciate any help on this.

Original source