Search code examples
javaspringunit-testingjunitpostconstruct

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


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.


Solution

  • Have a look at Spring JUnit Runner.

    You need to inject your class in your test class so that spring will construct your class and will also call post construct method. Refer the pet clinic example.

    eg:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:your-test-context-xml.xml")
    public class SpringJunitTests {
    
        @Autowired
        private Connection c;
    
        @Test
        public void tests() {
            assertEquals("arf arf arf", c.getX1();
        }
    
        // ...