问题描述
我有一个包含以下方法签名的接口:
I have a interface that contains the following method signature:
TResult GetValue<T, TResult>(object key, Expression<Func<T, TResult>> property) where T : class;
使用起订量,我可以嘲笑这种方法的一个特定的呼叫是这样的:
Using Moq, I'm able to mock a specific call of this method like this:
var repo = new Mock<IRepository>();
repo.Setup(r => r.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId)).Returns("SecretAgentId");
后来,当我这样做的呼叫
Then when I do this call
repo.Object.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId);
Tt的回报SecretAgentId
如我所料,所以一切都看起来很好。
Tt returns "SecretAgentId"
as I expect, so everything looks fine.
我的问题是,在我们的实际生产code,我们使用NSubstitute,而不是起订量。我试着用同样类型的安装位置:
My problem is that in our real production code we use NSubstitute, and not Moq. I tried using the same type of setup here:
var repo = Substitute.For<ICrmRepository>();
repo.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId).Returns("SecretAgentId");
不过,当我做下面的来电来访。
However, when I do the following call here
repo.GetValue<Customer, string>("SomeCustomerId", c => c.SecretAgentId);
它返回的,而不是SecretAgentId
我试图取代 C =&GT; c.SecretAgentId
与 Arg.Any&LT;防爆pression&LT; Func键&LT;客户,串&GT;&GT;&GT;()
如果只是为了看看它的工作原理,然后,再返回SecretAgentId
预期。但我需要验证它被称为与正确的前pression,而不是任何EX pression。
I tried replacing c => c.SecretAgentId
with Arg.Any<Expression<Func<Customer, string>>>()
just to see if it works then, and then it returns "SecretAgentId"
as expected. But I need to verify that it is called with the correct expression, and not just any expression.
所以,我需要知道,如果有可能得到这个NSubstitute工作,如果是,怎么了?
So I need to know if it is possible to get this to work in NSubstitute, and if it is, how?
推荐答案
我不记得确切的语法,所以请原谅我,如果这不是A1正确的,这是一个有点缺憾,但...
I can't remember exact syntax, so forgive me if this isn't A1 correct, and it is a bit kludgy but...
我相信你是在正确的轨道,当你试图Arg.Any,但尝试使用Arg.Is是这样的:
I believe you were on the right track when you tried Arg.Any, however try using Arg.Is like this:
Arg.Is<Expression<Func<Customer, string>>>(x => {
var m = ((Expression)x).Body as MemberExpression;
var p = m.Member as PropertyInfo;
return p.Name == "SecretAgentId";
});
这篇关于嘲笑了EX pression与NSubstitute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!