在单元测试中初始化配置



我在单元测试中遇到了一些初始化问题。我已经遇到这个问题一段时间了。

我有一个 EventProcessor 类,它是一个单例类。在构造函数中,我调用一个将读取配置文件的方法。

public class EventProcessor{
 // SingletonHolder is a container class to hold singleton instance 
private static final SingletonHolder<EventProcessor> m_EventProcessor = new SingletonHodler<>(new EventProcessor());
private EventProcessor() {
 Client client = ClientBuilder.newClient();
 String scheme = requiredHttps() ? "https" : "http";
 m_webTarget = client.target(scheme + ....);
}
// this method will get the singleton instance of this class
public static EventProcessor getAuditEventProcessor() {
    return m_EventProcessor.instance();
}
protected boolean requiredHttps() {
   // Configuration class is also a singleton and getConfig() is a static method
   //getSettings() will get key-value pair in the config file
  Map map = Configuration.getConfig().getSettings();  
  //do some check with the value in the map
 }
}

因此,当我启动整个项目时,另一个类将初始化配置类,我可以使用 requiredHttps() 读取配置文件。一切正常。但问题是当我编写单元测试时,配置类无法初始化。所以当我做类似的事情时EventProcessor.getAuditEventProcessor() 在测试类中并获取 ExceptionInInitializerError,由于从 Configuration.getConfig().getSettings() 获取 NullPointerException,无法初始化 EventProcessor 类;

对此有什么建议吗?

您可以创建static方法来初始化Configuration并使用@BeforeClass注释该方法。此方法将在测试类中的所有方法之前执行。

最新更新