How to moq a Func

跟風遠走 提交于 2019-12-01 15:15:29

问题


Trying to unit test a class whose constructor takes in a Func. Not sure how to mock it using 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:


figured it out

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


来源:https://stackoverflow.com/questions/6036708/how-to-moq-a-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!