最小起订量中的返回值过载 [英] Overloaded return values in MOQ
问题描述
我正在努力了解有关Moq的设置和单元测试的更多信息.不过,我遇到了一个小问题.
I'm working on understanding a bit more about Setup and unit testing with Moq. I've run into a slight problem though.
我想做的是这样的:
view.Setup(x => x.GetReference("object1")).Returns(object1);
view.Setup(x => x.GetReference("object2")).Returns(null);
但是,当我以这种方式进行调用时,我从未碰到会对Null语句做出反应的代码块.我应该如何设置我的安装程序,以便在由特定参数调用它们时以特定方式运行?
However, when I make my call this way, I never hit the block of code that would react to the Null statement. How am I supposed to set up my Setups so that they will behave in a specific way when they are called by a specific argument?
推荐答案
moq重载了两种返回值的方法:
The moq overloads two ways to return a value:
-
instance: Returns(instance);
-
delegate(Func<T>): Returns(()=>new Foo());
instance: Returns(instance);
delegate(Func<T>): Returns(()=>new Foo());
我认为问题是由于使用了Return方法的模棱两可引起的.
I think that the problem is caused from the ambiguousness for which Returns method is to be used.
因此,您需要通过以下方式为代码的第二个设置传递显式类型的NULL:
So, you need to pass in the explicit type of NULL for the second setup of your code as the following ways:
-
view.Setup(x => x.GetReference("object2")).Returns((ExplicitType)null);
-
view.Setup(x => x.GetReference("object2")).Returns(() => null);
view.Setup(x => x.GetReference("object2")).Returns((ExplicitType)null);
view.Setup(x => x.GetReference("object2")).Returns(() => null);
这篇关于最小起订量中的返回值过载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!