Moq - Linq expression in repository - Specify expression in setup
c#, linq, mocking, moq
Solution
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" });
Problem
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?