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

Settings variable values in a Moq Callback() call(在 Moq Callback() 调用中设置变量值)
本文介绍了在 Moq Callback() 调用中设置变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想我可能对 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() 调用中设置变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)