如何为 System.AppDomain class 创建 Shim?
How to create Shim for System.AppDomain class?
在我的代码中,我使用 AppDomain.CurrentDomain.BaseDirectory
调用。
在我的单元测试中,我想伪造这个调用,所以它总是 return 与 BaseDirectory
属性.
相同的值
但是,在为 System
生成假程序集后,我在单元测试中看不到 ShimAppDomain
。是因为 AppDomain
是 sealed class
吗?
如何将我的测试与 AppDomain.CurrentDomain.BaseDirectory
调用隔离?
使用 Microsoft Fakes Framework 和 Visual Studio 2015 Enterprise 进行模拟。
找到这个解决方案
我。将 mscorlib.fakes
的内容更新为
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
<Assembly Name="mscorlib" Version="4.0.0.0"/>
<StubGeneration>
<Clear/>
</StubGeneration>
<ShimGeneration>
<Clear/>
<Add FullName="System.AppDomain"/>
</ShimGeneration>
</Fakes>
二.添加 using System.Fakes
到我的单元测试文件
三。在我的单元测试中添加了以下内容
using (ShimsContext.Create())
{
string baseDir = @"My\Base\Dir";
ShimAppDomain fakeAppDomain = new ShimAppDomain()
{
BaseDirectoryGet = () => { return baseDir; }
};
ShimAppDomain.CurrentDomainGet = () => { return fakeAppDomain; };
string defaultDir = MyConstants.DefaultAppFolder;
// both baseDir and defaultDir are same "My\Base\Dir"
Assert.AreEqual(baseDir, defaultDir);
}
Constants.DefaultAppFolder
属性实现如下
internal static class MyConstants
{
internal static string DefaultAppFolder
{
get
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
}
它非常冗长,但有效。
在我的代码中,我使用 AppDomain.CurrentDomain.BaseDirectory
调用。
在我的单元测试中,我想伪造这个调用,所以它总是 return 与 BaseDirectory
属性.
但是,在为 System
生成假程序集后,我在单元测试中看不到 ShimAppDomain
。是因为 AppDomain
是 sealed class
吗?
如何将我的测试与 AppDomain.CurrentDomain.BaseDirectory
调用隔离?
使用 Microsoft Fakes Framework 和 Visual Studio 2015 Enterprise 进行模拟。
找到这个解决方案
我。将 mscorlib.fakes
的内容更新为
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/" Diagnostic="true">
<Assembly Name="mscorlib" Version="4.0.0.0"/>
<StubGeneration>
<Clear/>
</StubGeneration>
<ShimGeneration>
<Clear/>
<Add FullName="System.AppDomain"/>
</ShimGeneration>
</Fakes>
二.添加 using System.Fakes
到我的单元测试文件
三。在我的单元测试中添加了以下内容
using (ShimsContext.Create())
{
string baseDir = @"My\Base\Dir";
ShimAppDomain fakeAppDomain = new ShimAppDomain()
{
BaseDirectoryGet = () => { return baseDir; }
};
ShimAppDomain.CurrentDomainGet = () => { return fakeAppDomain; };
string defaultDir = MyConstants.DefaultAppFolder;
// both baseDir and defaultDir are same "My\Base\Dir"
Assert.AreEqual(baseDir, defaultDir);
}
Constants.DefaultAppFolder
属性实现如下
internal static class MyConstants
{
internal static string DefaultAppFolder
{
get
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
}
它非常冗长,但有效。