Øyv*_*hen 4 .net c# moq nsubstitute
我有一个包含以下方法签名的接口:
TResult GetValue<T, TResult>(object key, Expression<Func<T, TResult>> property) where T : class;
Run Code Online (Sandbox Code Playgroud)
使用Moq,我可以模拟这种方法的特定调用,如下所示:
var repo = new Mock<IRepository>();
repo.Setup(r => r.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId)).Returns("SecretAgentId");
Run Code Online (Sandbox Code Playgroud)
那我打电话的时候
repo.Object.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId);
Run Code Online (Sandbox Code Playgroud)
Tt "SecretAgentId"如我所愿返回,所以一切看起来都很好。
我的问题是,在实际的生产代码中,我们使用NSubstitute,而不是Moq。我尝试在此处使用相同类型的设置:
var repo = Substitute.For<ICrmRepository>();
repo.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId).Returns("SecretAgentId");
Run Code Online (Sandbox Code Playgroud)
但是,当我在这里打电话时
repo.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId);
Run Code Online (Sandbox Code Playgroud)
它返回“”而不是 "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"
}
Run Code Online (Sandbox Code Playgroud)