设置变量值的最小起订量回调()调用回调、最小、变量值、起订量

2023-09-02 11:56:40 作者:指尖上的温柔

我想我可能是对的起订量回调方法的语法有点混乱。当我尝试做这样的事情:

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>());

这抛出一个异常,因为 myFilteredFoos 演员LT在空; IFooBar&GT;()通话。难道这不是工作,我期待?我想 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 不能返回一个空它吸引我给它不会被调用的结论。此外,当我宣布 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;

在回拨抱怨myFilteredFoos可以使用它初始化之前。

The Return call complains that myFilteredFoos may be used before it is initialized.

推荐答案

这是因为code。在返回方法被立即评估;也就是说,当设置方法被调用。

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.

幸运的是,返回方法被重载,这样你可以推迟执行,以及:

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>());

不过,你不需要保存价值的回调,因为你可以得到的参数值直接在返回方法:

mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
    .Returns((IFilter filter) =>
        filter.FilterCollection(objects).Cast<IFooBar>());
 
精彩推荐
图片推荐