With Moq, how can I mock protected methods with an out parameter?

For a method like:

protected virtual bool DoSomething(string str) { }

I usually mock him:

var mockModule = new Mock<MyClass> { CallBase = true };
mockModule.Protected().Setup<bool>("DoSomething", ItExpr.IsAny<string>()).Returns(true);

But for a method like:

protected virtual bool DoSomething(out string str) { }

How can I mock this?

+4
source share
2 answers

This can be done with moq 4.8.0-rc1 (2017-12-08). You can use ItExpr.Ref<string>.IsAnyto match any value for refor out. In your case:

mockModule.Protected().Setup<bool>("DoSomething", ItExpr.Ref<string>.IsAny).Returns(true);

Full example with mocking out parameter:

[TestClass]
public class OutProtectedMockFixture
{
    delegate void DoSomethingCallback(out string str);

    [TestMethod]
    public void test()
    {
        // Arrange
        string str;
        var classUnderTest = new Mock<SomeClass>();
        classUnderTest.Protected().Setup<bool>("DoSomething", ItExpr.Ref<string>.IsAny)
            .Callback(new DoSomethingCallback((out string stri) =>
                {
                    stri = "test";
                })).Returns(true);

        // Act
        var res = classUnderTest.Object.foo(out str);

        // Assert
        Assert.AreEqual("test", str);
        Assert.IsTrue(res);
    }
}

public class SomeClass
{
    public bool foo(out string str)
    {
        return DoSomething(out str);
    }

    protected virtual bool DoSomething(out string str)
    {
        str = "boo";
        return false;
    }
}
+1
source

This can be done using Typemock Isolator , you can mock your non-public methods and easily change their parameters and ref parameters: / p>

[TestMethod, Isolated]
public void test()
{
    // Arrange
    string str;
    SomeClass classUnderTest = new SomeClass();
    Isolate.NonPublic.WhenCalled(classUnderTest, "DoSomething").AssignRefOut("test").IgnoreCall();

    // Act
    classUnderTest.foo(out str);

    // Assert
    Assert.AreEqual("test", str);
}


public class SomeClass
{
    public void foo(out string str)
    {
        DoSomething(out str);
    }

    protected virtual bool DoSomething(out string str) 
    {
        str = "boo";
        return true;
    }
}

.

-1

All Articles