如何使用Moq模拟一个Func函数

10

试图对一个构造函数接受 Func 参数的类进行单元测试。不确定如何使用 Moq 进行模拟。

public class FooBar
{
    public FooBar(Func<IFooBarProxy> fooBarProxyFactory)
    {
        _fooBarProxyFactory = fooBarProxyFactory;
    }
}



[Test]
public void A_Unit_Test()
{
    var nope = new Mock<Func<IFooBarProxy>>();
    var nope2 = new Func<Mock<IFooBarProxy>>();

    var fooBar = new FooBar(nope.Object);
    var fooBar2 = new FooBar(nope2.Object);

    // what's the syntax???
}
1个回答

9
我已经理解了。

弄明白了

public interface IFooBarProxy
{
    int DoProxyStuff();
}

public class FooBar
{
    private Func<IFooBarProxy> _fooBarProxyFactory;

    public FooBar(Func<IFooBarProxy> fooBarProxyFactory)
    {
        _fooBarProxyFactory = fooBarProxyFactory;
    }

    public int DoStuff()
    {
        var newProxy = _fooBarProxyFactory();
        return newProxy.DoProxyStuff();
    }
}

[TestFixture]
public class Fixture
{
    [Test]
    public void A_Unit_Test()
    {
        Func<IFooBarProxy> funcFooBarProxy = () =>
        {
            var mock = new Mock<IFooBarProxy>();
            mock.Setup(x => x.DoProxyStuff()).Returns(2);
            return mock.Object;
        };
        var fooBar = new FooBar(funcFooBarProxy);

        var result = fooBar.DoStuff();
        Assert.AreEqual(2, result);
    }
}

4
我认为你并没有嘲弄 Func,我认为你是从一个 Func 中返回了一个模拟对象。 - satnhak
如何设置以便测试在调用FooBar中的Func时返回的IFooBarProxy实例? - Jon
1
嘿@Jon,我添加了一个更完整的答案,演示如何对模拟对象进行断言。希望这有所帮助。 - kenwarner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接