How do you unit test a LINQ expression using Moq and Machine.Specifications?
- by Phil.Wheeler
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?