简体   繁体   English

使用MS Fakes进行密封类单例方法的填充

[英]shim a sealed class singleton method and with MS Fakes

i have a sealed class singleton Foo and its method: 我有一个密封类单例Foo及其方法:

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

and want to write a test for a method called FindFile using the GetFolderPath method like this: 并想要使用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);
    }

the problem is that i'm getting the following compilation error: 问题是我遇到以下编译错误:

Delegate does not take 0 arguments 委托不接受0个参数

In an similar Question How to shim OpenFileDialog.ShowDialog method the problem is solved like this : 在类似的问题中, 如何对OpenFileDialog.ShowDialog方法进行补片,该问题的解决方法如下:

[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);
    }
}

So i tried the same... according to the fact that GetFolderPath is a method with 1 Parameter... 所以我尝试了同样的方法...根据事实,GetFolderPath是带有1个参数的方法...

next problem is that i'm getting the following compilation error: 下一个问题是我遇到以下编译错误:

Delegate does not take 1 arguments 委托不接受1个参数

So my question is: 所以我的问题是:

Is it possible to shim a sealed class and particulary a singleton? 是否可以对密封班特别是单身人士进行垫料? And if so, what´s my mistake? 如果是这样,我的错误是什么?

thank you in anticipation 谢谢你的期待

Note that all shims assigned in the lifetime of ShimsContext will be destroyed after the ShimsContext is disposed. 请注意,在ShimsContext之后,将销毁在ShimsContext的生存ShimsContext分配的所有ShimsContext

In your sample, you are invoking WorkflowHelper.FindFile outside the using block that binds the lifetime of your ShimsContext , so the shimmed definition for Foo.GetFolderPath is no longer effective and the call to FindFile will use the original method definition. 在您的示例中,您在绑定了ShimsContext生存期的using块之外调用WorkflowHelper.FindFile ,因此Foo.GetFolderPath定义不再有效,并且对FindFile的调用将使用原始方法定义。

Just move your method call inside the using block and it will work: 只需将您的方法调用移到using块内,它将起作用:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM