Overloaded return values in MOQ

纵然是瞬间 提交于 2019-12-12 04:13:52

问题


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:

  1. instance: Returns(instance);
  2. 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:

  1. view.Setup(x => x.GetReference("object2")).Returns((ExplicitType)null);
  2. view.Setup(x => x.GetReference("object2")).Returns(() => null);


来源:https://stackoverflow.com/questions/11715191/overloaded-return-values-in-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!