如果您在要测试的类中具有一个依赖项的具体实现,那么经典解决方案是:添加一层间接性,使您拥有完全控制。
因此,需要添加越来越多的间接层(接口可以是单元测试中的存根/模拟)。
但问题在于:我必须在我的测试中使用依赖项的“真实”实现。那么怎么办呢?测试?不测试?
以这个例子为例:
我在应用程序中需要的路径上有一些依赖项。所以我提取了一个接口IPathProvider
(我可以在测试中伪造)。下面是实现:
public interface IPathProvider
{
string AppInstallationFolder { get; }
string SystemCommonApplicationDataFolder { get; }
}
具体实现
PathProvider
如下所示:public class PathProvider : IPathProvider
{
private string _appInstallationFolder;
private string _systemCommonApplicationDataFolder;
public string AppInstallationFolder
{
get
{
if (_appInstallationFolder == null)
{
try
{
_appInstallationFolder =
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
}
catch (Exception ex)
{
throw new MyException("Error reading Application-Installation-Path.", ex);
}
}
return _appInstallationFolder;
}
}
public string SystemCommonApplicationDataFolder
{
get
{
if (_systemCommonApplicationDataFolder == null)
{
try
{
_systemCommonApplicationDataFolder =
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
}
catch (Exception ex)
{
throw new MyException("Error reading System Common Application Data Path.", ex);
}
}
return _systemCommonApplicationDataFolder;
}
}
}
你会测试这样的代码吗?如果会,如何测试呢?