简体   繁体   中英

shim a sealed class singleton method and with MS Fakes

i have a sealed class singleton Foo and its method:

    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:

    [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

In an similar Question How to shim OpenFileDialog.ShowDialog method the problem is solved like this :

[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...

next problem is that i'm getting the following compilation error:

Delegate does not take 1 arguments

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.

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.

Just move your method call inside the using block and it will work:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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