问题描述
我想我可能对 Moq 回调方法的语法有些困惑.当我尝试做这样的事情时:
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>());
这会引发异常,因为在 Cast
调用期间 myFilteredFoos
为 null.这不按我的预期工作吗?我认为 FilterCollection
会被调用,然后 myFilteredFoos
将是非空的并允许强制转换.
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
无法返回 null,这让我得出结论,它没有被调用.另外,当我像这样声明 myFilteredFoos
时:
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;
Return 调用抱怨 myFilteredFoos 在初始化之前可能会被使用.
The Return call complains that myFilteredFoos may be used before it is initialized.
推荐答案
这是因为Returns
方法中的代码是立即求值的;也就是说,当调用 Setup
方法时.
This is because the code in the Returns
method is evaluated immediately; that is, when the Setup
method is being invoked.
但是,在调用 GetByFilter
方法之前不会调用回调.
However, the callback isn't being invoked until the GetByFilter
method is invoked.
幸运的是,Returns
方法已重载,因此您也可以延迟其执行:
Luckily, the Returns
method is overloaded so that you can defer its execution as well:
mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
.Callback((IFilter filter) =>
myFilteredFoos = filter.FilterCollection(objects))
.Returns(() => myFilteredFoos.Cast<IFooBar>());
但是,你不需要将值保存在回调中,因为你可以直接在 Returns
方法中获取参数值:
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:
mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
.Returns((IFilter filter) =>
filter.FilterCollection(objects).Cast<IFooBar>());
这篇关于在 Moq Callback() 调用中设置变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!