1

Why when I am trying to use a mock like this:

public void Test(string param=null){
    MyMock.Setup(x=>x.foo(param ?? It.IsAny<string>));
 }

This obviously works fine

public void Test(string param=null){
   if(param==null)
      MyMock.Setup(x=>x.foo(It.IsAny<string>));
   else
      MyMock.Setup(x=>x.foo(param));
 }

But why is that? the "param ?? It.IsAny" returns param or It.IsAny what am I missing here?

I saw this and this but I still don't get it.

Avner Huri
  • 111
  • 2
  • 8
  • Not sure this helps as I don't use Moq, but I tried the following and it coalesces as expected: List myValues = new List() { 4, null, 1 }; string Foo(int value) => value.ToString(); myValues.Select(x => Foo(x ?? 2)).ForEach(x => Console.WriteLine(x)); – Alenros Dec 24 '20 at 08:14

2 Answers2

2

When setting up Mock in Moq you actually pass not a value of function parameter (say, of tpye T), but an Expression<T>, which is then analyzed by Moq.
So, when you pass value Moq will analyze it and setup expectation for method call with that value.
When you pass It.IsAny<T> Moq will again analyze it and setup expectation without any arguments.
But when you pass your param ?? It.IsAny<string> Moq simply doesn't know how to analyze it.

Quercus
  • 2,015
  • 1
  • 12
  • 18
  • In the meanwhile I played with it and found out that if I just plug in a function like this:'Func f = ()=>param ?? It.IsAny();' to 'x.foo(f.Invoke())' it works fine. So if I get it correctly the first one leave the evaluation for later and fail, and this one evaluate it on the spot? – Avner Huri Dec 24 '20 at 12:07
-1
MyMock.Setup(x=>x.foo(param==null ? It.IsAny<string>:param));
zia khan
  • 361
  • 3
  • 14
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Dec 24 '20 at 08:35
  • Tried this, not working, and like DonaldDuck says I want to understand why. – Avner Huri Dec 24 '20 at 11:34