我刚刚创建了一个Manager,它处理一个SuperClass,它扩展到整个代码库并注册了某种SuperClassManager(SCM).
现在我想测试一下只知道SuperClass的经理.我尝试创建一个具体的SCM,但这取决于第三方库,因此我在jUnit测试中没有这样做.现在可以选择模拟此SCM的所有实例.
到目前为止一切都很好,但是,当我的经理处理SCM时,它会返回我的经理不知道或不关心的SuperClass的子项.然而,这些孩子的身份对我的测试(平等等)至关重要.
由于我不能使用具体的SCM,我必须模拟对SCM的相应功能的调用结果,但是,这意味着我的测试和(间接)我的经理需要知道并关心SuperClass的子项.
检查代码库,我的测试似乎没有更合适的位置(已经保持适当的实际依赖关系).
是否值得为单元测试引入不必要的依赖?
更新18 / DEC / 2012
这是我的问题的简化版本:
package some.package.declaration;
import some.open.source.framework.TopComponent;
import some.open.source.framework.WindowManager;
/**
* Own source code.
* Knows WindowManager and TopComponent; but no
* direct child of TopComponent.
*/
class TopComponentManager{
/**
*
*/
void efficientlyDoOperationsOnCurrentTopComponents(){
Set<TopComponent> currentTopComponents = get all current TopComponents from WindowManager;
Set<TopComponent> getNeededTopComponents(currentTopComponents);
do some operations on the current TopComponents;
...
...
}
void Set<TopComponent> getNeededTopComponents(Set<TopComponent> givenTopComponents){
Set<TopComponent> neededTopComponents = new HashSet<TopComponent>(givenTopComponents);
disregard and keep some TopComponents based on controls;
return neededTopComponents;
}
}
package some.package.declaration.test; // same project as TopComponentManager
import jmockit;
import some.open.source.framework.TopComponent;
import some.open.source.framework.WindowManager;
import own.source.code.childrenOfTopComponent.ChildTopComponent; // Don't want to; need to introduce package dependencies
import own.source.code.childrenOfTopComponent.AnotherChildTopComponent; // Don't want to; need to introduce package dependencies
class TopComponentManagerTest{
@Tested
TopComponentManager _topComponentManager;
@Mocked
WindowManager _windowManager;
@Mocked
ChildTopComponent _childTopComponent1; //extends TopComponent; unknown to both TopComponentManager and TopComponentManagerTest
@Mocked
AnotherChildTopComponent _childTopComponent2; //extends TopComponent; unknown to both TopComponentManager and TopComponentManagerTest
Set<TopComponent> _currentTopComponents = new HashSet<TopComponent>();
@Before
void setUp() throws Exception {
_currentTopComponents.add(_childTopComponent1);
_currentTopComponents.add(_childTopComponent2);
}
void testgetNeededTopComponents(){
Deencapsulation.invoke(_topComponentManager, "getNeededTopComponents", _currentTopComponents);
new Verifications(){{
verify that only _childTopComponent2 is returned;
}};
}
}
可以看出,在测试TopComponentManager时,我必须验证在此包中未知的已确定的必要元素.
最佳答案 为什么不直接模拟TopComponent?
例:
@Mocked
TopComponent _childTopComponent1;