I'm having an issue really testing the Querying side of my architecture where I'm calling into a repository that expects an Expression<Func<T, bool>>
as parameter for filtering. I was trying to understand this article, where Mark is saying to use Stubs for queries instead.
Lets say I have a query handler:
public class GetUserByEmailQueryHandler : IQueryHandler<GetUserByEmailQuery, User>
{
private readonly IGenericRepository<User> userRepository;
public GetUserByEmailQueryHandler(IGenericRepository<User> userRepository)
{
this.userRepository = userRepository;
}
public User Handle(GetUserByEmailQuery query)
{
return this.userRepository.Find(u => u.Email == query.Email && u.IsLockedOut == false);
}
}
Now my test is going to look something like this:
[Fact]
public void Correctly_Returns_Result()
{
// arrange
var id = Guid.NewGuid();
var email = "test@test.com";
var userRepositoryMock = new Mock<IGenericRepository<User>>();
userRepositoryMock.Setup(
r =>
r.Find(It.IsAny<Expression<Func<User, bool>>>())).Returns(new User { UserId = id }).Verifiable();
// Act
var query = new GetUserByEmailQuery(email);
var queryHandler = new GetUserByEmailQueryHandler(userRepositoryMock.Object);
var item = queryHandler.Handle(query);
// Assert
userRepositoryMock.Verify();
Assert.Equal(id, item.UserId);
}
To me, this test is useless, especially using It.IsAny<Expression<Func<User, bool>>>()
as I could be filtering by anything at all. The filter would be a crucial business logic that needs to be tested. How can I test an expression like this? Is this one of those reasons why a generic repository is bad and I should use a specific repository that take exactly the filter parameters that is needed? If that is the case, I'll be moving the expression from one layer to the other and I'd still need to test it
If I should use stubs as Mark said in his blog, are there any examples out there? Am I supposed to run this query on an in-memory list which will be used to validate that the filter expression is correct?