Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从shim方法调用原始方法_C#_Unit Testing_Microsoft Fakes_Shim - Fatal编程技术网

C# 从shim方法调用原始方法

C# 从shim方法调用原始方法,c#,unit-testing,microsoft-fakes,shim,C#,Unit Testing,Microsoft Fakes,Shim,为BCL(或任何库)中类型的成员创建垫片时。我们经常面临这样一种情况,即我们想要调用我们已经跳过的原始方法(无论是在shim委托内部还是外部)。例如: 在上面的代码中,当调用DateTime.Now时,我们要做的就是返回比实际日期短的一天。也许这看起来像是一个人为的例子,所以其他(更)现实的场景是 能够捕获并验证传递给特定方法的参数值 能够计算出一次事件的次数 特定的方法/属性由被测代码访问 我在一个真实的应用程序中遇到了最后一个场景,因此找不到关于伪造的答案。然而,在深入研究了Fakes文档之

为BCL(或任何库)中类型的成员创建垫片时。我们经常面临这样一种情况,即我们想要调用我们已经跳过的原始方法(无论是在shim委托内部还是外部)。例如:

在上面的代码中,当调用DateTime.Now时,我们要做的就是返回比实际日期短的一天。也许这看起来像是一个人为的例子,所以其他(更)现实的场景是

  • 能够捕获并验证传递给特定方法的参数值
  • 能够计算出一次事件的次数 特定的方法/属性由被测代码访问

  • 我在一个真实的应用程序中遇到了最后一个场景,因此找不到关于伪造的答案。然而,在深入研究了Fakes文档之后,我找到了答案,因此将其与社区问题一起发布。

    Fakes对此有一个内置的支持;事实上,要做到这一点,还有很多方法

    1) 使用ShimsContext.ExecuteWithoutShimmers()作为不需要填充行为的代码的包装器:

    System.Fakes.ShimDateTime.NowGet = () => 
    {
    return ShimsContext.ExecuteWithoutShims(() => DateTime.Now.AddDays(-1));
    };
    
    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;
    
    fakesdegresents.Func shim=null;
    垫片=()=>
    {
    System.Fakes.ShimDateTime.NowGet=null;
    var value=ShimsContext.executeWithoutFilms(()=>DateTime.Now.AddDays(-1));
    System.Fakes.ShimDateTime.NowGet=shim;
    返回值;
    };
    System.Fakes.ShimDateTime.NowGet=shim;
    
    编辑:显然第一种方法更简洁易读。因此,我更喜欢它,而不是显式声明shim变量并移除/恢复shim

    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;