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

AHu*_*ist 24 java junit spring unit-testing 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();
}
Run Code Online (Sandbox Code Playgroud)

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

mre*_*isz 22

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

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

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

  • init可以是私有的 (9认同)

Sri*_*r G 13

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

    // ...
Run Code Online (Sandbox Code Playgroud)

  • 我将通过在对象上调用@PostConstruct方法来对其进行测试。 (2认同)