Dav*_*iff 2 frameworks unit-testing
在进行单元测试时,总是很难知道你的框架有多低.
如果我们有一个直接依赖于.NET Framework的类,即System.IO.File类,那么我们真的无法单独测试它.
当然我们可以将它包装并将其注入依赖类,但随后我们开始包装每个.NET类!如果那个包装不是直接通话怎么办?也许它首先做一些检查/业务逻辑,你想要测试?
目前我们已经包装到一定程度,然后就不用费心单元测试那个包装器了.也许这没关系,因为它将在稍后通过集成和探索性测试进行测试?
这是C#中的一个例子,只是为了说明我的观点:
这个类与.NET Framework紧密耦合..很好,但是现在我不能单独测试它,它需要文件存在等等.
public class PathResolver
{
public string Resolve(string filename)
{
string completePath = string.Empty;
if(!File.Exists(filename))
{
return Path.Combine(@"D:\MyExample", filename);
}
return completePath;
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以通过以下方式对此进行单元测试:
public class PathResolver
{
private readonly IFileSystem _fileSystem;
public PathResolver(IFileSystem fileSystem)
{
_fileSystem = fileSystem;
}
public string Resolve(string filename)
{
string completePath = string.Empty;
if(!_fileSystem.Exists(filename))
{
return _fileSystem.Combine(@"D:\MyExample", filename);
}
return completePath;
}
}
Run Code Online (Sandbox Code Playgroud)
但现在我们无法测试"FileSystem"类!
其他人的想法是什么?