Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Match.Create in Moq

Tags:

c#

moq

I've got a strange behavior when using Match.Create with Moq.

The following code snippet doesn't pass, when I extract Match.Create as a variable:

      var mock = new Mock<IA>();
      mock.Object.Method ("muh");
      mock.Verify (m => m.Method (Match.Create<string> (s => s.Length == 3)));

      public interface IA
      {
        void Method (string arg);
      }

What is the reason?

like image 529
Matthias Avatar asked Jan 14 '13 19:01

Matthias


2 Answers

Thanks both of you. But I found another good solution for this. As in the quick start described, you can also use a method. First I thought it would make no difference, whether I use a variable or method. But obviously Moq is clever enough. So the expression and predicate stuff can be converted into:

public string StringThreeCharsLong ()
{
  return Match.Create<string> (s => s.Length == 3);
}

I think this is great, because it reduces the noise in unit tests.

MyMock.Verify (m => m.Method (StringThreeCharsLong());
like image 138
Matthias Avatar answered Oct 15 '22 22:10

Matthias


You're extracting too much. Predicate is enough:

var mock = new Mock<IA>();
Predicate<string> isThreeCharsLong = s => s.Length == 3;
mock.Object.Method("muh");
mock.Verify(m => m.Method(Match.Create<string>(isThreeCharsLong)));

Alternatively, for the same effect but slightly shorter syntax you can use It.Is matcher with expression parameter:

var mock = new Mock<IA>();
Expression<Func<string, bool>> isThreeCharsLong = s => s.Length == 3;
mock.Object.Method("muh");
mock.Verify(m => m.Method(It.Is<string>(isThreeCharsLong)));
like image 26
k.m Avatar answered Oct 15 '22 23:10

k.m