在Moq Callback()调用中设置变量值


69

我想我可能对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>());

抛出异常,因为myFilteredFoosCast<IFooBar>()调用期间为null 。这不是我期望的那样吗?我认为FilterCollection会被调用,然后myFilteredFoos将为非null并允许强制转换。

FilterCollection不能返回空值,这使我得出不被调用的结论。另外,当我这样声明时myFilteredFoos

Queryable myFilteredFoos;

Return调用抱怨myFilteredFoos可能在初始化之前使用。

Answers:


100

这是因为该Returns方法中的代码会立即求值。也就是说,当Setup方法被调用时。

但是,在调用GetByFilter方法之前,不会调用回调。

幸运的是,该Returns方法已重载,因此您也可以延迟其执行:

mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
    .Callback((IFilter filter) =>
        myFilteredFoos = filter.FilterCollection(objects))
    .Returns(() => myFilteredFoos.Cast<IFooBar>());

但是,您不需要将值保存在回调中,因为您可以直接在Returns方法中获取参数值:

mockObject.Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
    .Returns((IFilter filter) =>
        filter.FilterCollection(objects).Cast<IFooBar>());

20

您只需在返回值中使用参数即可...

mockObject
  .Setup(m => m.GetByFilter(It.IsAny<IFilter>()))
  .Returns((IFilter filter) =>
    {
      myFilteredFoos = filter.FilterCollection(objects);

      return myFilteredFoos.Cast<IFooBar>();
    });

嗯 这就是我想要的:)
Bimal Das
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.