在 Moq Callback() 调用中设置变量值
我想我可能对 Moq 回调方法的语法有点困惑。当我尝试执行以下操作时:
IFilter filter = new Filter();
List<IFoo> objects = new List<IFoo> { new Foo(), new Foo() };
IQueryable myFilteredFoos = null;
mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
.Callback( (IFilter filter) => myFilteredFoos = filter.FilterCollection(objects))
.Returns(myFilteredFoos.Cast<IFooBar>());
这会引发异常,因为在 Cast
调用期间 myFilteredFoos
为 null。这不符合我的预期吗?我认为 FilterCollection
将被调用,然后 myFilteredFoos
将是非空的并允许强制转换。
FilterCollection 无法返回 null,这让我得出结论,它没有被调用。另外,当我像这样声明 myFilteredFoos
时:
Queryable myFilteredFoos;
Return 调用抱怨 myFilteredFoos 可能在初始化之前被使用。
I think I may be a bit confused on the syntax of the Moq Callback methods. When I try to do something like this:
IFilter filter = new Filter();
List<IFoo> objects = new List<IFoo> { new Foo(), new Foo() };
IQueryable myFilteredFoos = null;
mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
.Callback( (IFilter filter) => myFilteredFoos = filter.FilterCollection(objects))
.Returns(myFilteredFoos.Cast<IFooBar>());
This throws a exception because myFilteredFoos
is null during the Cast<IFooBar>()
call. Is this not working as I expect? I would think FilterCollection
would be called and then myFilteredFoos
would be non-null and allow for the cast.
FilterCollection
is not capable of returning a null which draws me to the conclusion it is not being called. Also, when I declare myFilteredFoos
like this:
Queryable myFilteredFoos;
The Return call complains that myFilteredFoos may be used before it is initialized.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为
Returns
方法中的代码会立即计算;也就是说,当调用Setup
方法时。但是,在调用
GetByFilter
方法之前,不会调用回调。幸运的是,
Returns
方法已重载,因此您也可以推迟其执行:但是,您不需要在回调中保存该值,因为您可以直接在
返回
方法:This is because the code in the
Returns
method is evaluated immediately; that is, when theSetup
method is being invoked.However, the callback isn't being invoked until the
GetByFilter
method is invoked.Luckily, the
Returns
method is overloaded so that you can defer its execution as well:However, you don't need to save the value in a callback, because you can just get the parameter value directly in the
Returns
method:您可以直接在返回值中获取参数...
You can just take the parameter in the return value...
这是因为如果我们使用
Return(GetObject2(object1))
object1 从未从回调中初始化,那么我们如何使用Return
方法,因此它将无法转换为Object2
正确的使用方法是这样的
Return(()=> GetObject2())
,我们让 Return 方法指定一个函数,该函数将计算该方法返回的值不要忘记使用功能键
()=>
下面的示例,供您参考
This is because the way how are we using
Return
methodif we are using
Return(GetObject2(object1))
object1 never got initialized from callback, so it will fail to convert to Object2The Right way to use like this
Return(()=> GetObject2())
, we have make Return method specifies a function that will calculate the value to return from the methodDon't forgot to use funcation key
()=>
Below Example, For your reference