【发布时间】:2015-12-02 01:55:51
【问题描述】:
我正在使用 WELD-SE 进行依赖注入的 Java SE 环境中进行编程。因此一个类的依赖看起来像这样:
public class ProductionCodeClass {
@Inject
private DependencyClass dependency;
}
在为此类编写单元测试时,我正在为 DependencyClass 创建一个模拟,并且由于我不想为我运行的每个测试启动一个完整的 CDI 环境,我手动“注入”模拟:
import static TestSupport.setField;
import static org.mockito.Mockito.*;
public class ProductionCodeClassTest {
@Before
public void setUp() {
mockedDependency = mock(DependencyClass.class);
testedInstance = new ProductionCodeClass();
setField(testedInstance, "dependency", mockedDependency);
}
}
静态导入的方法setField()我用我在测试中使用的工具在一个类中编写了自己:
public class TestSupport {
public static void setField(
final Object instance,
final String field,
final Object value) {
try {
for (Class classIterator = instance.getClass();
classIterator != null;
classIterator = classIterator.getSuperclass()) {
try {
final Field declaredField =
classIterator.getDeclaredField(field);
declaredField.setAccessible(true);
declaredField.set(instance, value);
return;
} catch (final NoSuchFieldException nsfe) {
// ignored, we'll try the parent
}
}
throw new NoSuchFieldException(
String.format(
"Field '%s' not found in %s",
field,
instance));
} catch (final RuntimeException re) {
throw re;
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
}
我不喜欢这个解决方案的一点是,我在任何新项目中都需要这个助手。我已经将它打包为一个 Maven 项目,我可以将其作为测试依赖项添加到我的项目中。
但是在我缺少的其他一些公共库中没有现成的东西吗?一般情况下,我有什么方法可以做到这一点?
【问题讨论】:
-
使用构造函数注入。
标签: java unit-testing mockito cdi