【问题标题】:How to moq a Func如何起订量功能
【发布时间】:2011-08-27 13:26:59
【问题描述】:

尝试对构造函数采用 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???
}

【问题讨论】:

    标签: .net unit-testing mocking moq func


    【解决方案1】:

    想通了

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

    【讨论】:

    • 我不认为你已经模拟了 Func 我认为你正在从 Func 返回一个模拟对象。
    • 如何设置它以便测试一个 IFooBarProxy 实例,当您在 FooBar 中调用 Func 时将返回该实例?
    • 嘿@Jon,我添加了一个更完整的答案,演示了如何对模拟对象进行断言。我希望这会有所帮助
    猜你喜欢
    • 1970-01-01
    • 2015-07-14
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多