【问题标题】:shim a sealed class singleton method and with MS Fakes垫片密封类单例方法和 MS Fakes
【发布时间】:2014-08-06 11:07:02
【问题描述】:

我有一个密封类单例 Foo 及其方法:

    public string GetFolderPath(FooFolder folder)
    {
        IBoo boo = this.GetBoo();
        return boo.GetFolderPath(folder);
    }

并想使用 GetFolderPath 方法为 FindFile 方法编写测试,如下所示:

    [TestMethod]
    public void FindFile()
    {   
        string expectedPath = Path.Combine(Path.GetTempPath(), "TestPath");
        using (ShimsContext.Create())
        {
            Fakes.ShimFoo.AllInstances.GetFolderPathFolder
                = () => { return "C:\\...\\Temp"; };

        }
        string actualPath = WorkflowHelper.FindFile("TestPath");
        Assert.AreEqual(expectedPath, actualPath);
    }

问题是我收到以下编译错误:

委托不接受 0 个参数

在类似的问题How to shim OpenFileDialog.ShowDialog method 中,问题是这样解决的:

[TestMethod]
public void SomeTest()
{
    using (var context = ShimsContext.Create())
    {
        Nullable<bool> b2 = true;
        ShimCommonDialog.AllInstances.ShowDialog = (x) => b2;

        var sut = new Sut();

        var r = sut.SomeMethod();

        Assert.IsTrue(r);
    }
}

所以我尝试了同样的方法...根据 GetFolderPath 是一个具有 1 个参数的方法的事实...

下一个问题是我收到以下编译错误:

Delegate 不接受 1 个参数

所以我的问题是:

是否可以填充密封类,特别是单例?如果是这样,我的错误是什么?

谢谢你的期待

【问题讨论】:

  • 第二次你到底尝试了什么?
  • 所以你找到了解决方案。
  • 有一次我尝试使用 0 参数然后我发现了这个类似的问题并且厌倦了 1 参数......所以我有编译错误:不需要 1 参数......但那是我的错误。根据GetFolderPath是一个参数的方法,Lambda表达式有2个参数
  • 所以没有编译错误了......对此感到抱歉......但还有另一个问题......编译工作但 GetFolderPath 方法不返回填充结果。对此我感到非常抱歉...我只是开发中的新手...但这导致了我的实际问题...感谢您的快速回复 Alireza
  • 为什么 GetFolderPath 不返回填充结果?这很简单。现有方法将被新定义取代。把问题告诉我,我会帮你的

标签: c# microsoft-fakes


【解决方案1】:

请注意,在 ShimsContext 的生命周期内分配的所有 shim 将在 ShimsContext 被处置后被销毁。

在您的示例中,您在绑定 ShimsContext 的生命周期的 using 块之外调用 WorkflowHelper.FindFile,因此 Foo.GetFolderPath 的填充定义不再有效,对 FindFile 的调用将使用原始方法定义.

只需将您的方法调用移动到 using 块内,它就会起作用:

    using (ShimsContext.Create())
    {
        Fakes.ShimFoo.AllInstances.GetFolderPathFolder = ...; // your lambda expression

        string actualPath = WorkflowHelper.FindFile("TestPath");
    }
    Assert.AreEqual(expectedPath, actualPath);

【讨论】:

  • 好吧,对我来说太愚蠢了......这很容易......谢谢一千次:D
  • 很抱歉忽略了这么简单的事情:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多