c# - 用 NSubstitute 模拟表达式

标签 c# .net moq nsubstitute

我有一个包含以下方法签名的接口(interface):

TResult GetValue<T, TResult>(object key, Expression<Func<T, TResult>> property) where T : class;

使用 Moq,我可以像这样模拟此方法的特定调用:

var repo = new Mock<IRepository>();
repo.Setup(r => r.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId)).Returns("SecretAgentId");

然后当我做这个调用时

repo.Object.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId);

Tt 返回 "SecretAgentId"如我所料,所以一切看起来都很好。

我的问题是,在我们真正的生产代码中,我们使用的是 NSubstitute,而不是 Moq。我在这里尝试使用相同类型的设置:

var repo = Substitute.For<ICrmRepository>();
repo.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId).Returns("SecretAgentId");

但是,当我在这里调用下面的代码时

repo.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId);

它返回 ""而不是 "SecretAgentId"

我尝试替换 c => c.SecretAgentIdArg.Any<Expression<Func<Customer, string>>>()只是为了看看它是否有效,然后它返回 "SecretAgentId"正如预期的那样。但我需要验证它是用正确的表达式调用的,而不仅仅是任何表达式。

所以我需要知道是否有可能让它在 NSubstitute 中工作,如果可以,怎么做?

最佳答案

我认为表达式在 NSubstitute 中的计算取决于它们的闭包范围,因此两个表达式声明并不相同。对我来说这看起来像是一个错误,你可能想打开一个问题。

但是您可以从替换声明中取出表达式并且它可以正常工作:

private static void Main(string[] args)
{
    Expression<Func<string, string>> myExpression =  s => s.Length.ToString();
    var c = Substitute.For<IRepo>();
    c.GetValue<string, string>("c", myExpression).Returns("C");

    var result = c.GetValue<string, string>("c", myExpression); // outputs "C"
}

关于c# - 用 NSubstitute 模拟表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26120821/

相关文章:

c# - 如何最小起订量设置索引属性

c# - 每个团队成员和分支的不同 *.csproj/*.config 设置

c# - 等于 System.Collections.Generic.List<T>... 的方法?

c# - 模拟数据访问器

c# - 当我调用 ThrowIfCancellationRequested() 时,OperationCanceledException 未被用户代码处理

javascript - 类型 System.Collections.Generic.IDictionary 不支持反序列化数组

c# - 用参数模拟一个方法

c# - 为什么 GetRequestToken 不起作用?

c# - Visual Studio 2017 中没有模板

c# - Array.Sort 静态函数的 Lambda 表达式不明确