Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to moq a Func

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???
}
like image 273
kenwarner Avatar asked May 17 '11 20:05

kenwarner


People also ask

How do you mock the func in MOQ?

Moq can fake explicit delegates by simply passing their type to the constructor. var mock = new Mock<ParseString>(); Alternatively, Moq supports delegates based on Func and Action . var mock = new Mock<Func<string, int>>();

How to mock a function in c#?

Trying to mock a method that is called within another method. // code part public virtual bool hello(string name, int age) { string lastName = GetLastName(); } public virtual string GetLastName() { return "xxx"; } // unit test part Mock<Program> p = new Mock<Program>(); p. Setup(x => x. GetLastName()).


1 Answers

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);
    }
}
like image 116
kenwarner Avatar answered Oct 09 '22 21:10

kenwarner