Trouble mocking a private method

275 Views Asked by At

So, I am having an issue mocking a private method. From everything I have seen it should work, but isn't.

Let's start with the basics - Here is the code under test

public sealed class UnderTest
{
    private bool MockPrivate(string name)
    {
        [snip]
    }

    private string MethodUnderTest(ParameterHolder parameters)
    {
        if (!this.MockPrivate(parameters.Parameter2))
        {
            return null;
        }
        [Snip]
    }
    [Snip]
}

public sealed class ParameterHolder 
{
    public ParameterHolder (bool parameter1, string parameter2)
    {
        this.Parameter1  = parameter1;
        this.Parameter2 = parameter2;
    }

    public bool Parameter1
    {
        get;
        private set;
    }

    public string Parameter2
{
        get;
        private set;
    }
}

Here is the test method

public void Test_UnderTest_MethodUnderTest()
{
    UnderTest testClass;
    ParameterHolder parameters;
    dynamic h;

    testClass = new UnderTest();

    parameters = Isolate.Fake.Instance<ParameterHolder>(Members.CallOriginal);
    Isolate.WhenCalled(() => parameters.Parameter1).WillReturn(true);
    Isolate.WhenCalled(() => parameters.Parameter2).WillReturn("parameter2value");

    h = testClass.AsDynamic();

    Isolate.WhenCalled(() => h.MockPrivate((string)null)).WillReturn(true);

    Assert.IsNotNull(h.MethodUnderTest(parameters));
}

I have also tried to change the isolate call to:

Isolate.WhenCalled(() => h.MockPrivate("parameter2value").WillReturn(true);

and

Isolate.WhenCalled(() => h.MockPrivate(parameters.Parameter2).WillReturn(true);

In all the cases, the MockPrivate method gets executed, instead of returning the mocked True value.

Any help would be appreciated.

1

There are 1 best solutions below

0
Chad Yost On

Ok, did some more checking and this is the correct way:

Isolate.NonPublic.WhenCalled(testClass, "MockPrivate").WillReturn(true);