如何使用Spring测试具有@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方法没有被击中。

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

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

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

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

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

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

要么