如何起订量函数求 [英] How to moq a Func

查看:137
本文介绍了如何起订量函数求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图单元测试类的构造函数的函数功能。不知道如何用最小起订量来模拟它。

 公共类FooBar的
{
    公共FooBar的(Func键< IFooBarProxy> fooBarProxyFactory)
    {
        _fooBarProxyFactory = fooBarProxyFactory;
    }
}



[测试]
公共无效A_Unit_Test()
{
    VAR都能跟得上=新的模拟< Func键< IFooBarProxy>>();
    VAR nope2 =新的函数功能:LT;模拟< IFooBarProxy>>();

    Foobar的VAR =新的FooBar的(nope.Object);
    VAR fooBar2 =新FooBar的(nope2.Object);

    //什么语法???
}
 

解决方案

想通了

 公共接口IFooBarProxy
{
    INT DoProxyStuff();
}

公共类FooBar的
{
    私有函数功能:LT; IFooBarProxy> _fooBarProxyFactory;

    公共FooBar的(Func键< IFooBarProxy> fooBarProxyFactory)
    {
        _fooBarProxyFactory = fooBarProxyFactory;
    }

    公众诠释DoStuff()
    {
        变种newProxy = _fooBarProxyFactory();
        返回newProxy.DoProxyStuff();
    }
}

[的TestFixture]
公共类灯具
{
    [测试]
    公共无效A_Unit_Test()
    {
        FUNC< IFooBarProxy> funcFooBarProxy =()=>
        {
            VAR模拟=新的模拟< IFooBarProxy>();
            mock.Setup(X => x.DoProxyStuff())返回(2)。
            返回mock.Object;
        };
        Foobar的VAR =新的FooBar的(funcFooBarProxy);

        VAR的结果= fooBar.DoStuff();
        Assert.AreEqual(2结果);
    }
}
 

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???
}

解决方案

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

这篇关于如何起订量函数求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆