【发布时间】:2014-12-16 22:10:04
【问题描述】:
我有一个简单的Java动态工厂模式(实际上是groovy,但出于所有目的,我们可以假设是java),它接收一个操作并通过从属性文件中读取相应的属性文件来动态加载该特定操作的处理程序名字。
该模式很简单,只需使用具有以下签名的基本方法:
class ReflectionFactory implements BaseFactory {
PropertyReader propertyReader
public ReflectionFactory(PropertyReader reader) {
this.propertyReader = reader
}
Adapter resolveAdapter(String serviceName) {
// TODO: Find service configuration in propertyReader and load via class loader
return defaultAdapter
}
}
类中的功能尚未实现,我想使用 TDD 来实现它,也就是说,我想创建一个测试来验证,给定一个 serviceName,它将返回一个适当类型的类。
加载类的代码类似于:
String className = propertyReader.getProperty(serviceName)
this.class.classLoader.loadClass(className, true, false)
在我看来,我需要“模拟”类加载器,但显然我不想引入注入类只是为了替换这一行:
this.class.classLoader.loadClass(className, true, false)
有什么方法可以测试使用正确的参数调用类加载器吗?换句话说,有没有办法“模拟”或“替换”类加载器的调用?
理想情况下我可以做到(伪代码)
when(classLoader.loadClass("serviceName", true, false)).thenReturn(dummyClassInstance)
所以测试代码看起来像:
void testWhenResolveServiceAndClassPropertyDefinedInstansceIsCreated() {
serviceName = "myService"
when(propertyReader.getPropertyValue("myService")).thenReturn("com.mydomain.adapters.testAdapter")
when(classLoader.loadClass("com.mydomain.adapters.testAdapter", true, false)).thenReturn(testDummy)
def factory = new ReflectionFactory(propertyReader)
def adapter = factory.resolveAdapter(serviceName)
assertNotNull(adapter)
verify(classloader).loadClass("com.mydomain.adapters.testAdapter", true, false)
}
我使用 Mockito 作为模拟框架,但欢迎任何模拟框架/解决方案
【问题讨论】:
-
在我尝试之前,您能否提供完整的 ReflectionFactory 实现示例并进行测试(以及何时)?可能无法编译并且无法正常工作 - 只想了解整个情况。
-
实现是我定义的,也就是功能还没有实现。查看编辑后的问题,了解我要编写的测试的详细信息
-
谢谢,将在 UTC 晚上试一试。
标签: java unit-testing dynamic reflection groovy