Moq with lambda expressions?

I am trying to test the application service using Moq 4.0.10827 (on NuGet) and you need to request the repository:

public class MyService
{
    Repository<MyObject> _Repo;

    public MyObject Get (string SomeConstraint)
    {
        return _Repo
            .GetTheFirstOneOrReturnNull (M => M.Constraint.Equals (
                SomeContraint, StringComparison.InvariantCultureIgnoreCase
            ));  // GetTheFirstOneOrReturnNull takes a Func<MyObject, bool>
    }
}

How to reproduce lambda expression using moq? I keep getting the Unsupported Expression exception.

Here is the idea of ​​what I'm doing already:

[TestMethod]
public void GetByMyConstraintShouldReturnWithMyObject ()
{
    // Arrange
    const string MyConstraint = "Constraint";
    MyObject Expected = new MyObject { Constraint = MyConstraint };
    Mock<Repository<MyObject>> MockRepo = new Mock<Repository<MyObject>> ();
    MockRepo.Setup (x => x.GetTheFirstOneOrReturnNull (M => 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 ();

}

I looked through some other answers, but can't figure out what I'm doing wrong (admittedly, "noob" with Moq). I came to the conclusion that it will be a pain, but I have many tests like this, and I want it to be hard now, instead of drowning later.

lambda ? , , .

+3
3

. , FirstOrDefault , , Func , , Repository.

+1

, . , , .

, youre , . , , IRepository.

+1

, Repository, - FindByConstraint, , , Constraint, Repo FirstOrDefault(). , , , - , , , .

I personally have difficulty testing an object to keep in mind my design, and I find that objects that are easy to verify deserve attention.

+1
source

All Articles