How do you unit test a LINQ expression using Moq and Machine.Specifications?

Posted by Phil.Wheeler on Stack Overflow See other posts from Stack Overflow or by Phil.Wheeler
Published on 2010-04-15T10:17:17Z Indexed on 2010/04/15 22:03 UTC
Read the original article Hit count: 455

I'm struggling to get my head around how to accommodate a mocked repository's method that only accepts a Linq expression as its argument. Specifically, the repository has a First() method that looks like this:

public T First(Expression<Func<T, bool>> expression)
{
    return All().Where(expression).FirstOrDefault();
}

The difficulty I'm encountering is with my MSpec tests, where I'm (probably incorrectly) trying to mock that call:

public abstract class with_userprofile_repository
{
    protected static Mock<IRepository<UserProfile>> repository;

    Establish context = () =>
    {
        repository = new Mock<IRepository<UserProfile>>();
        repository.Setup<UserProfile>(x => x.First(up => up.OpenID == @"http://testuser.myopenid.com")).Returns(GetDummyUser());
    };

    protected static UserProfile GetDummyUser()
    {
        UserProfile p = new UserProfile();
        p.OpenID = @"http://testuser.myopenid.com";
        p.FirstName = "Joe";
        p.LastLogin = DateTime.Now.Date.AddDays(-7);
        p.LastName = "Bloggs";
        p.Email = "[email protected]";

        return p;
    }
}

I run into trouble because it's not enjoying the Linq expression:

System.NotSupportedException: Expression up => (up.OpenID = "http://testuser.myopenid.com") is not supported.

So how does one test these sorts of scenarios?

© Stack Overflow or respective owner

Related posts about machine.specifications

Related posts about moq