我有一个包含以下方法签名的接口(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.SecretAgentId
与 Arg.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/