如何使用Spring测试具有@PostConstruct方法的类的构造函数?

时间:2012-05-09 09:19:11

标签: java spring unit-testing junit postconstruct

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

我错过了一些明显的东西吗?

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方法没有被击中。

4 个答案:

答案 0 :(得分:21)

如果Connection的唯一容器管理部分是您的@PostContruct方法,只需在测试方法中手动调用它:

@Test
public void test() {
  Connection c = new Connection("dog", "ruff");
  c.init();
  assertEquals("arf arf arf", c.getX1());
}

如果有更多,如依赖等,你仍然可以手动注入它们,或者 - 正如Sridhar所说 - 使用spring test framework。

答案 1 :(得分:12)

查看Spring JUnit Runner

您需要在测试类中注入您的类,以便spring将构造您的类,并且还将调用post构造方法。参考宠物诊所的例子。

例如:

@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 :(得分:0)

@PostConstruct必须改变对象的状态。所以,在JUnit测试用例中,获取bean后检查对象的状态。如果它与@PostConstruct设置的状态相同,则测试成功。

答案 3 :(得分:0)

默认情况下,Spring不会知道@PostConstruct和@PreDestroy注释。要启用它,您必须注册'CommonAnnotationBeanPostProcessor'或在bean配置文件中指定''。

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

<context:annotation-config />

相关问题