问题
I'm working on understanding a bit more about Setup and unit testing with Moq. I've run into a slight problem though.
What I want to do is something like this:
view.Setup(x => x.GetReference("object1")).Returns(object1);
view.Setup(x => x.GetReference("object2")).Returns(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?
回答1:
The moq overloads two ways to return a value:
instance: Returns(instance);
delegate(Func<T>): Returns(()=>new Foo());
I think that the problem is caused from the ambiguousness for which Returns method is to be used.
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);
来源:https://stackoverflow.com/questions/11715191/overloaded-return-values-in-moq