问题描述
我有一个工厂类来检索我的应用程序的配置:
I have a factory class to retrieve the configuration for my application:
public class ConfigurationFactory {
private static ConfigurationFactory configurationFactory = new ConfigurationFactory();
private Configuration configuration = null;
public static ConfigurationFactory getConfigurationFactory() {
return configurationFactory;
}
一些getConfiguration方法取决于我从哪里获取配置(文件,数据库,默认等...):
And some getConfiguration methods depending on where I am getting the config from (file, database, default, etc...):
public Configuration getConfiguration(String path){...}
public Configuration getConfiguration(String database){...}
我的问题是当我做单元测试时对于每个方法,我必须重新启动单例以便从不同的源加载,所以我唯一想到的就是添加它:
My problem is that when I do unit test for each method, I have to restart the singleton in order to load from a different source, so the only thing I had come up to is adding this:
public void resetConfiguration() {
this.configuration = null;
}
而且我觉得我会因为这样做而烧掉开发人员的地狱:)
And I feel I'll burn in developer's hell for doing it :)
我的问题:如果不添加此方法,还有其他方法吗?
My question: Is there any other way to do it without adding this method?
注意:我见过我不能使用像Spring或Guice这样的任何DI框架,管理层认为添加一个框架会使项目变得重量级,因为这个程序是打算运行的服务器上的守护进程。
Note: I have seen this and I cannot use any DI framework like Spring or Guice, management thinks adding a framework would make the project heavyweight, as this program is intended to run as a daemon on servers.
推荐答案
我能想到的一些事情是
-
使用模拟框架,如
Easymock
或Mockito
来模拟ConfigurationFactory
并在其他调用区域使用这个模拟对象。
Use mocking frameworks like
Easymock
orMockito
to mock theConfigurationFactory
and use this mock objects in other calling areas.
在 ConfigurationFactory 类并定义一个注释,如 @TestPurpose
,并使用它来覆盖单元测试中的单例对象。注释是表示在应用程序流程中不应该使用它,并且该函数仅用于junit目的。
Have a setter defined in the ConfigurationFactory
class and define an annotation like @TestPurpose
and use this to override the singleton object from your unit tests. The annotation is to denote that this should not be used during the application flow and the function is meant only for junit purpose.
这篇关于用jUnit测试单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!