Here is my code:
[TestMethod]
public void LoginUnregisteredUserShouldFail()
{
Mock<IRepository<User>> _repo = new Mock<IRepository<User>>();
UserServiceForTest target = new UserServiceForTest(_repo.Object, new HashingService());
var unregisteredTestUser = new User() { Email = "a", Nombre = "test", Password = "test" };
var registeredHashedTestUser = new User() { Email = "test@test.com", Nombre = "test", Password = "qUqP5cyxm6YcTAhz05Hph5gvu9M=" };
Expression<Func<User, bool>> expression = a => a.Email == "a";
_repo.Setup(a => a.Single(It.Is<Expression<Func<User,bool>>>(l => l.ToString() == expression.ToString()))).Returns(unregisteredTestUser);
Assert.IsFalse(target.ValidateCredentials(unregisteredTestUser));
}
I want to query the Single method of my repo, matching Email, and I want the result to be the specified User.
I dont know what I’m doing wrong but I always receive null.
EDIT:
My implementation is the following:
private string GetUserPasswordFromDbByUserName(string userName)
{
Expression<Func<User, bool>> ax = a => a.Email == userName;
var axx = ax.ToString();
var user = _repo.Single(ax);
if (user != null)
return user.Password;
else
return string.Empty;
}
It receives a string userName and for some reason, the .ToString() returns ‘a => (a.Email == value(Casita.Services.UserService+<>c__DisplayClass5).userName)’ instead of ‘a => (a.Email == “a”)’. Makes no sense to me, but I’m guessing this is the reason the comparison is failing.
Your problem is likely the equality comparison in the Is expression parameter. They are probably not the same when converted to strings so your equality comparison might be failing. The following question details how to compare [Func] delegates:
How to check if two Expression<Func<T, bool>> are the same
Nievely I’ll suggest the following might work. Note this would use http://evain.net/blog/articles/2008/02/06/an-elegant-linq-to-db4o-provider-and-a-few-linq-tricks which might require adding a reference/download of db4o. I stopped research at that point.
At any rate the core problem is probably that comparison.
Marc Gravell’s answer seems to imply using the method your using will work, but only if everything including variables in the implementation of your actual method are exactly the same and are passed in that exact same state in the call to the repository dependency.
My understanding of this is you would have to have exactly the same definition of the expression that you are using for testing and in the actual implementation this is testing.
I would try debugging and looking at each expression converted to a string (the one in your test method and the one in your implementation, and check if they are exactly the same. If they are then that theory is out the window.)
It weakens your test, but you could just check if any expression is passed in and return what you want.
Another alternative that may work for you is checking if the returns of the delegates are the same, but again this is a weaker test: