Gen*_*e S 2 c# unit-testing microsoft-fakes visual-studio-2012
我正在将我们的单元测试从Moles转换为新的VS 2012 Fakes.我们的几个单元测试"假" RNGCryptoServiceProvider.我们能够"mole"这个,但似乎在假货中没有为它创造了Shim.换句话说,我希望找到一个ShimRNGCryptoServiceProvider.
更有趣的一点是,我在网上找到了一本名为"使用Microsoft Fakes进行更好的单元测试"的电子书.在那里,他们展示了伪造随机函数的一个例子.这是一个例子.
System.Fakes.ShimRandom.Constructor = (real) => { };
System.Fakes.ShimRandom.AllInstances.NextDouble = this.NextDouble;
System.Fakes.ShimRandom.AllInstances.NextInt32Int32 = this.NextInt32Int32;
private int NextInt32Int32(Random random, int i, int arg3)
{
return (i + arg3) / 2;
}
Run Code Online (Sandbox Code Playgroud)
我甚至没有在我的项目中看到System.Fakes.ShimRandom.我看到 的唯一两个垫片System.Fakes是ShimDateTime和ShimGuid.
我确实看到了一堆Stubs,包括System.Fakes.StubRandom和System.Fakes.StubRandomNumberGenerator,但是Stubs对我不起作用,因为我无法将它们注入到被测试的代码中.
RNGCryptoServiceProvider?MS Fakes框架目前不支持这些类型.

另一种查找不支持类型的方法是,在.fakes文件中添加Diagnostic = true例如.
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic ="true">
<Assembly Name="mscorlib" Version="4.0.0.0"/>
Run Code Online (Sandbox Code Playgroud)
更新
请注意,你不能假装一切.这也意味着你也无法完成任何事情.由于一些设计考虑因素,MS决定不对某些系统类进行Shim.没有明确的MS提供的列表,因为根据用户的.NET版本和目标.NET框架的组合,可以伪造类型.例如,在.NET 4中,System.Security中的某些成员,System.Threading Fakes中的类型将不会生成为Shims.
您可以尝试覆盖此行为,例如将以下xml添加到.Fakes文件中
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic ="true">
<Assembly Name="mscorlib" Version="4.0.0.0"/>
<ShimGeneration>
<Add FullName="System.Security.Cryptography"/>
</ShimGeneration>
</Fakes>
Run Code Online (Sandbox Code Playgroud)
以上内容会产生我在上面的答案中提供的相同警告.这意味着它们不受支持.
但正如我之前所说,它是.NET版本和目标框架的组合.如果您可以更改目标.NET frameowork,例如.NET 2,仍然使用mscorlib版本4.0.0.0,您会看到为RNGCryptoServiceProvider生成Shim get .
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true" TargetFrameworkVersion="2.0.0.0">
<Assembly Name="mscorlib" Version="4.0.0.0"/>
<ShimGeneration>
<Clear/>
<Add FullName="System.Security.Cryptography"/>
</ShimGeneration>
</Fakes>
Run Code Online (Sandbox Code Playgroud)
这同样适用于RandomNumberGenerator.
