简体   繁体   English

Lambda表达式参数

[英]Lambda expression arguments

I'm trying to create an extension method for Moq where I can send in an expression to be used in an async return function. 我正在尝试为Moq创建一个扩展方法,我可以在其中发送一个表达式,用于异步返回函数。 However this question is not really Moq specific. 但是这个问题并不是特定的Moq。 Here's what I have so far: 这是我到目前为止所拥有的:

public static IReturnsResult<TMock> ReturnsAsync<TMock, TResult, T>(this IReturns<TMock, Task<TResult>> setup, Func<T, TResult> valueFunc) where TMock : class
{
    return setup.Returns(Task.FromResult(valueFunc.Invoke(default(T))));
}

This is how I'm hoping to use it. 这就是我希望使用它的方式。

repo.Setup(x => x.FindAsync(It.IsAny<Expression<Func<T, bool>>>())).ReturnsAsync((Expression<Func<T, bool>> e) => context.GetSet<T>().FirstOrDefault(e));

Now I don't really know how all of this works and the thing I can't figure out is how to I get the expression passed on into the ReturnsAsync function so I can use it as the argument instead of the default(T) that I put there as a placeholder. 现在我真的不知道所有这些是如何工作的,我无法弄清楚的是如何将表达式传递给ReturnsAsync函数,因此我可以将它用作参数而不是默认值(T)我把它作为占位符。

As expected the "e" variable here becomes null. 正如预期的那样,“e”变量在此变为空。

This method will do what you want: 这个方法可以做你想要的:

public static IReturnsResult<TMock> ReturnsAsync<TMock, TResult, T>(
        this IReturns<TMock, Task<TResult>> setup, 
        Func<Expression<Func<TResult, T>>, TResult> valueFunc)
    where TMock : class
{
    return setup.Returns<Expression<Func<TResult, T>>>(
        e => Task.FromResult(valueFunc(e)));
}

Then use it like so: 然后像这样使用它:

repo.Setup(x => x.FindAsync(It.IsAny<Expression<Func<T, bool>>>()))
    .ReturnsAsync<IRepository, int, bool>(e => context.GetSet<T>().FirstOrDefault(e));

Essentially, this version of ReturnsAsync takes a function that expects a predicate function (which is e ) and returns a T . 本质上,此版本的ReturnsAsync采用一个期望谓词函数(即e )并返回T函数。 This allows you to then execute the predicate against your test data set ( context.GetSet<T>.FirstOrDefault ). 这允许您对测试数据集执行谓词( context.GetSet<T>.FirstOrDefault )。 Also, I used the overload of Returns that accepts a type parameter; 另外,我使用了接受类型参数的Returns的重载; this is used to forward the arguments from the Setup call to the function specified as the Returns argument. 这用于将Setup调用中的参数转发给指定为Returns参数的函数。

Your version's signature only specified the predicate, so you had no way to execute it against your test data. 您的版本的签名仅指定了谓词,因此您无法针对测试数据执行它。 You also had the T and TResult type parameters backwards in the valueFunc parameter's type. 您还在valueFunc参数的类型中向后反转了TTResult类型参数。

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

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