Var*_*n K 4 c# unit-testing shim microsoft-fakes
为BCL(或任何库)中的类型成员创建填充程序时.我们经常面临一种情况,我们想要调用我们已经覆盖的原始方法(无论是在垫片代理内部还是外部).例如:
System.Fakes.ShimDateTime.NowGet = () => DateTime.Now.AddDays(-1);
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,调用DateTime.Now时我们想要做的就是返回一个小于实际日期的日期.也许这看起来像一个人为的例子,所以其他(更多)现实的场景是
我面对真实应用中的最后一个场景,无法找到Fakes on SO的答案.但是,在深入了解Fakes文档后,我找到了答案,因此将其与社区问题一起发布.
假货有内置的支持; 实际上有两种方法可以实现这一点.
1)使用ShimsContext.ExecuteWithoutShims()作为不需要填充行为的代码的包装:
System.Fakes.ShimDateTime.NowGet = () =>
{
return ShimsContext.ExecuteWithoutShims(() => DateTime.Now.AddDays(-1));
};
Run Code Online (Sandbox Code Playgroud)
2)另一种方法是将垫片设置为null,调用原始方法并恢复垫片.
FakesDelegates.Func<DateTime> shim = null;
shim = () =>
{
System.Fakes.ShimDateTime.NowGet = null;
var value = ShimsContext.ExecuteWithoutShims(() => DateTime.Now.AddDays(-1));
System.Fakes.ShimDateTime.NowGet = shim;
return value;
};
System.Fakes.ShimDateTime.NowGet = shim;
Run Code Online (Sandbox Code Playgroud)
编辑:显然,第一种方法更简洁,更易读.所以我更喜欢它明确声明shim变量和删除/恢复垫片.
| 归档时间: |
|
| 查看次数: |
3799 次 |
| 最近记录: |