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

被刻印的时光 ゝ 提交于 2019-12-12 09:28:59

问题


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.


回答1:


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

    // ...



回答2:


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.




回答3:


@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.




回答4:


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 />



来源:https://stackoverflow.com/questions/10513167/how-to-test-constructor-of-a-class-that-has-a-postconstruct-method-using-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!