尝试将方法组作为参数传递

时间:2012-11-01 13:34:01

标签: c# generics delegates stub microsoft-fakes

使用Microsoft伪造我的存根对象中有以下方法签名:

 public void GetAllOf1ExpressionOfFuncOfT0M0Int32Int32<T2>(FakesDelegates.Func<Expression<System.Func<T, T2>>, int, int, IList<T>> stub);

这是真正的存根方法:

  IList<T> GetAll<T2>(Expression<Func<T, T2>> orderbyexpr, int nStartAt = -1, int NumToSel = -1);

我想要做的是使用此方法为stub方法分配自定义内容:

  public static RunReport StubMethod<T>(ref FakesDelegates.Func<T> func, T returnValue) 
    {
        var counter = new RunReport();

        func = () =>
                   {
                       Interlocked.Increment(ref counter.Count);
                           return returnValue;
                   };
        return counter;
    }

我遇到的问题是我无法理解StubMethod的签名是什么,我怎么称呼它?

我尝试了几件导致我&#34;方法组无法分配/不能投出方法组的事情&#34;。

BTW - 它与其他更简单的存根方法完美配合:

    IList<T> IRepository<T>.GetAll();

所以一定是定义问题......

这是我在代码中使用GetAll的地方......这应该重定向到我的自定义函数:

  public IList<EntityType> GetAllEntityTypesByName(string filter)
    {
        IList<EntityType> types = new List<EntityType>();
        try
        {
            using (IUnitOfWork uow = ctx.CreateUnitOfWork(true))
            {
                IRepository<EntityType> repType = uow.CreateRepository<EntityType>();
                if (string.IsNullOrEmpty(filter))
                {
                    types = repType.GetAll(o => o.Name);
                }
                else
                {
                    types = repType.Find(t => t.Name.ToLower().Contains(filter.ToLower()), o => o.Name);
                }
            }
        }
        catch (Exception e)
        {
            ResourceManager.Instance.Logger.LogException(e);
        }
        return types;
    }

另一种看待问题的方法是我想要替换它:

stubRepType.GetAllOf1ExpressionOfFuncOfT0M0Int32Int32<string>((a, b, c) => { return new List<EntityType>(); });

用这个:

TestHelper.StubRepositoryMethod<IList<EntityType>>(ref stubRepType.GetAllOf1ExpressionOfFuncOfT0M0Int32Int32<string>, new List<EntityType>());

1 个答案:

答案 0 :(得分:1)

首先尝试使用具体类型。这是一个有效的例子。

[TestMethod]
public void TestMethod1()
{
    var stub = new StubIRepository<DateTime>();
    stub.GetAllOf1ExpressionOfFuncOfT0M0Int32Int32<int>(this.StubGetAll);
    var target = (IRepository<DateTime>)stub;
    IList<DateTime> datesByMonth = target.GetAll(date => date.Month);
    Assert.AreEqual(2005, datesByMonth[0].Year);
}

IList<DateTime> StubGetAll(Expression<Func<DateTime, int>> orderByExpr, int startIndex = -1, int numberOfItems = -1)
{
    var allDates = new[] {
        new DateTime(2001, 12, 1),
        new DateTime(2002, 11, 1),
        new DateTime(2003, 10, 1),
        new DateTime(2004, 9, 1),
        new DateTime(2005, 8, 1)
    };

    Func<DateTime, int> orderByFunc = orderByExpr.Compile();

    return allDates.OrderBy(orderByFunc).ToList();
}