How to moq a Func

前端 未结 1 475
余生分开走
余生分开走 2021-01-17 17:00

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

        
1条回答
  •  旧巷少年郎
    2021-01-17 17:39

    figured it out

    public interface IFooBarProxy
    {
        int DoProxyStuff();
    }
    
    public class FooBar
    {
        private Func _fooBarProxyFactory;
    
        public FooBar(Func fooBarProxyFactory)
        {
            _fooBarProxyFactory = fooBarProxyFactory;
        }
    
        public int DoStuff()
        {
            var newProxy = _fooBarProxyFactory();
            return newProxy.DoProxyStuff();
        }
    }
    
    [TestFixture]
    public class Fixture
    {
        [Test]
        public void A_Unit_Test()
        {
            Func funcFooBarProxy = () =>
            {
                var mock = new Mock();
                mock.Setup(x => x.DoProxyStuff()).Returns(2);
                return mock.Object;
            };
            var fooBar = new FooBar(funcFooBarProxy);
    
            var result = fooBar.DoStuff();
            Assert.AreEqual(2, result);
        }
    }
    

    0 讨论(0)
提交回复
热议问题