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

后端 未结 4 2083
遇见更好的自我
遇见更好的自我 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();
        }
    
        // ...
    

提交回复
热议问题