Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test constructor of a class that has a @PostConstruct method using Spring?

Tags:

If I have a class with a @PostConstruct method, how can I test its constructor and thus its @PostConstruct method using JUnit and Spring? I can't simply use new ClassName(param, param) because then it's not using Spring -- the @PostConstruct method is not getting fired.

Am I missing something obvious here?

public class Connection {     private String x1;     private String x2;      public Connection(String x1, String x2) {         this.x1 = x1;         this.x2 = x2;     }      @PostConstruct     public void init() {         x1 = "arf arf arf";     }  }   @Test public void test() {     Connection c = new Connection("dog", "ruff");     assertEquals("arf arf arf", c.getX1()); } 

I have something similar (though slightly more complex) than this and the @PostConstruct method does not get hit.

like image 807
AHungerArtist Avatar asked May 09 '12 09:05

AHungerArtist


People also ask

What does @PostConstruct do 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 do you test a constructor?

To test that a constructor does its job (of making the class invariant true), you have to first use the constructor in creating a new object and then test that every field of the object has the correct value. Yes, you need need an assertEquals call for each field.

In what order do the @PostConstruct annotated method the Init method?

Correct? Despite you use asynchronized method, these postConstruct methods wil be executed sequentially. Then, ServiceA#init() will be finished when ServiceB#init() will begin.

Can we have multiple PostConstruct?

In a single class, it allows to have more than one @PostConstruct annotated method, and also the order of execution is random.


1 Answers

If the only container managed part of Connection is your @PostContruct method, just call it manually in a test method:

@Test public void test() {   Connection c = new Connection("dog", "ruff");   c.init();   assertEquals("arf arf arf", c.getX1()); } 

If there is more than that, like dependencies and so on you can still either inject them manually or - as Sridhar stated - use spring test framework.

like image 82
mrembisz Avatar answered Oct 17 '22 22:10

mrembisz