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

标签 java spring unit-testing junit postconstruct

如果我有一个带有@PostConstruct 方法的类,我如何使用JUnit 和Spring 测试它的构造函数以及它的@PostConstruct 方法?我不能简单地使用 new 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 方法没有受到影响。

最佳答案

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

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

如果还有更多,例如依赖项等,您仍然可以手动注入(inject)它们,或者 - 正如 Sridhar 所说 - 使用 spring 测试框架。

关于java - 如何使用 Spring 测试具有 @PostConstruct 方法的类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10513167/

相关文章:

python - 以编程方式检测是否正在测试 python 代码

java - 创建测试数据 : domain builder

java - com.fasterxml.jackson.databind.JsonMappingException : no suitable constructor found, 无法从对象值反序列化

java - 使用 JmsTemplate 发送到 ActiveMQ 时出现文本消息编码问题

java - 具有反序列化列表对象的 Spring Controller

java - Hibernate 4 延迟加载不起作用

java - 制作一个单jar java应用程序

java - 使用 Volley MultiPart 上传 PDF、文档、视频

unit-testing - 在编写源代码之前如何编写单元测试?

objective-c - 为什么当我测试一个方法抛出异常并且该方法抛出异常时,测试会停止?