Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For a method like:

protected virtual bool DoSomething(string str) { }

I usually mock it through:

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 it?

like image 788
Mike Avatar asked May 27 '16 02:05

Mike


1 Answers

It can be done since moq 4.8.0-rc1 (2017-12-08). You can use ItExpr.Ref<string>.IsAny for match any value for ref or out parameters. In your case:

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

Full example with mocking the 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;
    }
}
like image 111
itaiy Avatar answered Sep 25 '22 02:09

itaiy