简体   繁体   English

泛型-如何将Lambda表达式传递给方法?

[英]generics - How to pass a lambda expression into a method?

I have a number of business service classes that I'm setting up unit tests for. 我有许多要为其设置单元测试的业务服务类。

In mocking the data, I've got a fairly generic set of methods. 在模拟数据时,我有一组相当通用的方法。 One to provide a mocked dbSet, one to provide a service. 一个提供模拟的dbSet,另一个提供服务。

One thing I haven't managed to make generic as yet is the process of mocking the data context. 我还没有设法使它通用的一件事是模拟数据上下文的过程。

Right now I have something like: 现在我有类似的东西:

mockDbSet = MyHelper.GetMockedDbSet(myData); // myData is an IQueryable List <T>
mockContext = new Mock<MyDataContext>();
// A handful of general .Setup lines snipped here
mockContext.Setup(m => m.Person).Returns(mockDbSet.Object);

Every unit test fixture is the same except for the last line, which the 除了最后一行,每个单元测试夹具都相同。

m => m.Person

is substituted for some other entity. 被其他实体替代。

All entities share the same base classes. 所有实体共享相同的基类。

What I'm after is something like this: 我所追求的是这样的:

mockContext = MyHelper.GetMockedDbContext(m => m.Person);

and be able to put all this generic code into the helper class. 并能够将所有这些通用代码放入helper类。

I can't work out how to implement GetMockedDbContext , though. 不过,我不知道如何实现GetMockedDbContext

Here's what I've got so far: 到目前为止,这是我得到的:

public static Mock<MyDataContext> GetMockedDbContext(Func<MyDataContext, object> func)
{
    var context = new Mock<MyDataContext>();

    // Now what?

    return context;
}

UPDATE: Here's what I've ended up doing so far. 更新:这是我到目前为止所做的。 Something like this was posted as an answer, and then deleted. 像这样的内容被发布为答案,然后被删除。 It seems to work. 它似乎有效。

public static Mock<MyDataContext> GetMockedDbContext<TResult>(Expression<Func<MyDataContext, TResult>> func, TResult result)
{
    var context = new Mock<MyDataContext>();
    // Snipped out stuff
    context.Setup(func).Returns(result);
    return context;
}

Your method's parameter should be of the same type as Setup method's parameter is, which means your method has to be generic too: 您的方法的参数应该与Setup方法的参数具有相同的类型,这意味着您的方法也必须是通用的:

public static Mock<MyDataContext> GetMockedDbContext<T>(Expression<Func<MyDataContext, T>> func)
{
    var context = new Mock<MyDataContext>();

    // Now what?
    context.Setup(func).Returns(mockDbSet.Object);

    return context;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM