Announcement Announcement Module
Collapse
No announcement yet.
How to test constructor of a class that has a @PostConstruct method using Spring? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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?

    Code:
    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. I would like to avoid having to create multiple bean definitions in a config file just to test this constructor. Is there some way I can use some Spring classes to trigger the @PostConstruct to get fired?

  • #2
    Originally posted by AHungerArtist View Post
    I have something similar (though slightly more complex) than this and the @PostConstruct method does not get hit. I would like to avoid having to create multiple bean definitions in a config file just to test this constructor. Is there some way I can use some Spring classes to trigger the @PostConstruct to get fired?
    Your Connection is instantiated using new keyword. As stated in the javadoc of @PostConstruct, this annotation must be processed by Dependency Injection, which I believe is any DI framework. The new keyword does not invoke any DI framework to provide the instance of Connection class.

    You may try putting @Configurable at the class level to ask Spring to handle new keyword (even this way I have not tested if Spring will call @PostConstruct. It handles @Autowired though). Please read Spring reference documentation about using @Configurable.

    Comment


    • #3
      What is it you want to test? Don't you trust spring in calling the method? Or do you simply want to unit test this class, if it is the latter don't use spring but simply create the class, call the init method yourself and run your tests. If you need other objects you are really doing an integration test and not a unit test.

      Comment

      Working...
      X