本文介绍了如何使用Spring测试具有@PostConstruct方法的类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带有@PostConstruct方法的类,我如何使用JUnit和Spring测试其构造函数及其@PostConstruct方法?我不能简单地使用新的ClassName(param,param),因为它不使用Spring - @PostConstruct方法没有被解雇。

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

我有类似的东西(虽然稍微复杂一点)并且@PostConstruct方法没有被击中。

I have something similar (though slightly more complex) than this and the @PostConstruct method does not get hit.

推荐答案

有看看。

你需要在你的测试类中注入你的类,这样spring将构造你的类,并且还会调用post构造方法。宠物诊所的例子。

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.

例如:

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

    // ...

这篇关于如何使用Spring测试具有@PostConstruct方法的类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 09:55