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

后端 未结 4 2112
遇见更好的自我
遇见更好的自我 2021-02-18 13:12

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

相关标签:
4条回答
  • 2021-02-18 13:25

    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();
        }
    
        // ...
    
    0 讨论(0)
  • 2021-02-18 13:25

    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.

    0 讨论(0)
  • 2021-02-18 13:38

    By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register ‘CommonAnnotationBeanPostProcessor‘ or specify the ‘‘ in bean configuration file.

    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

    or

    <context:annotation-config />

    0 讨论(0)
  • 2021-02-18 13:46

    @PostConstruct must be changing the state of the object. So, in JUnit test case, after getting the bean check the state of the object. If it is same as the state set by @PostConstruct, then the test is success.

    0 讨论(0)
提交回复
热议问题