我有一个工厂类来检索我的应用程序的配置:
public class ConfigurationFactory {
private static ConfigurationFactory configurationFactory = new ConfigurationFactory();
private Configuration configuration = null;
public static ConfigurationFactory getConfigurationFactory() {
return configurationFactory;
}
还有一些 getConfiguration 方法,具体取决于我从何处获取配置(文件、数据库、默认值等...):
public Configuration getConfiguration(String path){...}
public Configuration getConfiguration(String database){...}
我的问题是,当我对每个方法进行单元测试时,我必须重新启动单例才能从不同的源加载,所以我唯一想到的就是添加这个:
public void resetConfiguration() {
this.configuration = null;
}
而且我觉得我会因为这样做而在开发人员的 hell 中燃烧:)
我的问题:如果不添加此方法,还有其他方法吗?
注:我看过this而且我不能使用任何 DI 框架,如 Spring 或 Guice,管理层认为添加框架会使项目重量级,因为该程序旨在作为服务器上的守护进程运行。
最佳答案
我能想到的一些事情是
使用
Easymock
或Mockito
等模拟框架来模拟ConfigurationFactory
并在其他调用区域使用此模拟对象。在
ConfigurationFactory
类中定义一个 setter 并定义一个注释,例如@TestPurpose
,并使用它来覆盖单元测试中的单例对象。注释是为了表示在应用程序流程中不应使用它,并且该函数仅用于 junit 目的。
关于java - 使用 jUnit 测试单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10510894/