.Net Fakes-当基类是抽象的时,如何填充继承的属性



我正在尝试编写一个单元测试,该测试涵盖以下行

var fileFullName = fileInfo.FullName;

其中fileInfo是fileInfo的一个实例。

我使用fakes填充FileInfo对象,但无法为FullName属性提供值,因为它是从基类继承的。

对于没有继承的Name属性,我可以简单地这样做:

ShimFileInfo.AllInstances.NameGet = info => OriginalFullName;

Microsoft提供的答案是在基类上创建填充程序,在本例中为FileSystemInfo。但如果我尝试这个:

ShimFileSystemInfo.AllInstances.FullNameGet = info => OriginalFullName;

它不起作用,因为FileSystemInfo是一个抽象类,无法创建,因此无法填充。

在这种特殊的情况下,我可以绕过它,因为我可以将DirectoryName和Name属性组合起来使其可测试,但我不能只使用我想要的属性,这似乎很疯狂,因为它恰好来自基础。

有人遇到这个问题并设法解决了吗?

您说过填充基类不起作用,但我确实这么做了,它在我们的测试中起作用。

System.dll中的FileInfo被定义为FileInfo : FileSystemInfo,而FileSystemInfo在mscorlib中。默认情况下,mscorlib中的许多类型都没有填充,但如果您将其添加到mscorlib.fakes文件中:

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="mscorlib" Version="4.0.0.0"/>
  <ShimGeneration>
    <Add FullName="System.IO.FileSystemInfo"/>
  </ShimGeneration>
</Fakes>

然后构建您的测试项目,您可以从mscorlib获得FileSystemInfoShimFileSystemInfo,以及从System.dll获得FileInfoShimFileInfo

using (ShimsContext.Create())
{
    var directoryName = "<testPath>";
    var fileName = "test.txt";
    ShimFileSystemInfo.AllInstances.FullNameGet = @this => "42";
    result = new DirectoryInfo(directoryName).GetFiles(fileName).First();
    Assert.AreEqual("42", result.FullName);   // the fake fullname
    Assert.AreEqual("test.txt", result.Name); // the real name
}

Caveat:适用于我的机器(Visual Studio 2013,.NET 4.5.1)

fakes文件的参考:Microsoft fakes 中的代码生成、编译和命名约定

最新更新