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.
Annotation Type PostConstruct The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.
When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.
The method SalesDataAggregate is running on startup because of the @PostConstruct annotation. If you want to keep it from running during tests you can create the class containing the post construct in your test folder and add the @primary annotation so it takes precedence over the class in your main project.
We can replace @PostConstruct with BeanFactoryPostProcessor and PriorityOrdered interface. The first one defines an action that ought to be executed after the object's instantiation. The second interface tells the Spring the order of the component's initialization.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With