-->

Moq - Linq expression in repository - Specify expr

2020-06-13 08:39发布

问题:

I have a method on my interface that looks like:

T GetSingle(Expression<Func<T, bool>> criteria);

I'm trying to mock the setup something like this (I realise this isn't working):

_mockUserRepository = new Mock<IRepository<User>>();
_mockUserRepository.Setup(c => c.GetSingle(x => x.EmailAddress == "a@b.com"))
    .Returns(new User{EmailAddress = "a@b.com"});

I realise I'm passing in the wrong parameter to the setup.
After reading this answer I can get it working by passing in the Expression, like this:

_mockUserRepository.Setup(c => c.GetSingle(It.IsAny<Expression<Func<User, bool>>>())
    .Returns(new User{EmailAddress = "a@b.com"});

However, this means if I call the GetSingle method with any expression, the same result is returned.

Is there a way of specifying in the setup, what Expression to use?

回答1:

If you don't mind a generic set up, it can be simpler like this.

_mockUserRepository.Setup(c => c.GetSingle(It.IsAny<Expression<Func<User, bool>>>()))
    .Returns(new User { EmailAddress = "a@b.com" });


回答2:

I managed to get this to work:

Expression<Func<User, bool>> expr = user => user.EmailAddress == "a@b.com";

_mockUserRepository.Setup(c => c.GetSingle(It.Is<Expression<Func<User, bool>>>(criteria => criteria == expr)))
    .Returns(new User { EmailAddress = "a@b.com" });

User result = _mockUserRepository.Object.GetSingle(expr);