【发布时间】:2009-09-23 21:16:38
【问题描述】:
我正在处理一些现有的代码,试图添加它并增加它的单元测试。但是在让代码可测试时遇到了一些问题。
原始构造函数:
public Info() throws Exception
{
_ServiceProperties = new ServiceProperties();
_SshProperties = new SshProperties();
}
我知道这很糟糕,而且显然无法测试。在 junit 环境中,此类将无法每次创建,因为它无法找到构建自身所需的属性。现在,我知道通过移动以“new”开头的任何内容作为参数的简单更改,这个类将更具可测试性。
所以我最终得到:
新构造函数:
public Info(ServiceProperties srvProps, SshProperties sshProps) throws Exception
{
_ServiceProperties = srvProps;
_SshProperties = sshProps;
}
这让我可以正确地对这个 Info 类进行单元测试。但问题是,现在所有的工作都被推到了其他类:
其他类的方法:
public void useInfo() throws Exception
{
ServiceProperties srvProps = new ServiceProperties();
SshProperties sshProps = new SshProperties();
Info info = new Info(srvProprs, sshProprs);
doStuffWithInfo(info);
}
现在这个方法是不可测试的。我所能做的就是将这些 Property 对象的构造推到发生的地方,而在其他地方,一些代码实际上会被卡住,实际上不得不调用“new”。
这对我来说是个难题:我不知道如何打破将这些“新”调用简单地推送到其他地方的事件链。我错过了什么?
【问题讨论】:
标签: java unit-testing refactoring constructor