title: Moq with lambda expressions?
body: <p>I am trying to test an application service using Moq 4.0.10827 (on NuGet) and need to query a repository:</p>
  
  <pre><code>public class MyService
  {
      Repository&lt;MyObject&gt; _Repo;
  
      public MyObject Get (string SomeConstraint)
      {
          return _Repo
              .GetTheFirstOneOrReturnNull (M =&gt; M.Constraint.Equals (
                  SomeContraint, StringComparison.InvariantCultureIgnoreCase
              ));  // GetTheFirstOneOrReturnNull takes a Func&lt;MyObject, bool&gt;
      }
  }
  </code></pre>
  
  <p>How do I replicate the lambda expression with Moq?  I keep getting the "Unsupported expression" exception.</p>
  
  <p>Here is an idea of what I'm doing already:</p>
  
  <pre><code>[TestMethod]
  public void GetByMyConstraintShouldReturnWithMyObject ()
  {
      // Arrange
      const string MyConstraint = "Constraint";
      MyObject Expected = new MyObject { Constraint = MyConstraint };
      Mock&lt;Repository&lt;MyObject&gt;&gt; MockRepo = new Mock&lt;Repository&lt;MyObject&gt;&gt; ();
      MockRepo.Setup (x =&gt; x.GetTheFirstOneOrReturnNull (M =&gt; M.Constraint.Equals (MyConstraint, StringComparison.InvariantCultureIgnoreCase)))
              .Returns (Expected).Verifable ();
      MyService Service = new MyService (MockRepo.Object);
  
      // Act
      MyObject Result = Service.Get (MyConstraint);
  
  
      // Assert
      Assert.AreSame (Expected, Result);
      MockRepo.Verify ();
  
  }
  </code></pre>
  
  <p>I've looked around at some of the other answers but I cannot really make out what I am doing incorrectly (admittedly a "noob" with Moq).  I have come to the conclusion that this is going to be a pain but I have a lot of tests like this coming up and want to get solid now instead of drowning later.</p>
  
  <p>Is the only option to encapsulate the lambda expression inside of an object and pass in the repository and have it execute the query?  I don't want to change my code just for my testing environment, but I don't want to waste time trying to bend this thing to my will, either.</p>