简体   繁体   中英

Overloaded return values in MOQ

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM