使用 Moq,如何模拟没有参数的受保护方法? [英] With Moq, how can I mock protected methods with out parameter?

查看:30
本文介绍了使用 Moq,如何模拟没有参数的受保护方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于像这样的方法:

protected virtual bool DoSomething(string str) { }

我通常会嘲笑它:

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) { }

我该如何模拟它?

推荐答案

从 moq 4.8.0-rc1 (2017-12-08) 开始可以实现.您可以使用 ItExpr.Ref.IsAny 来匹配 refout 参数的任何值.在你的情况下:

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

这篇关于使用 Moq,如何模拟没有参数的受保护方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆