Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PostConstruct not called when using Mockito @Spy annotation

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.

like image 839
javalearner Avatar asked Feb 22 '14 17:02

javalearner


People also ask

What is the use of @PostConstruct annotation?

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.

What is @PostConstruct annotation in spring?

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.

How can Postconstructs be prevented?

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.

What can I use instead of PostConstruct?

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.


1 Answers

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();
}
like image 82
JB Nizet Avatar answered Sep 28 '22 09:09

JB Nizet