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

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.


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();
    }

    // ...