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 == "[email protected]"))
.Returns(new User{EmailAddress = "[email protected]"});
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 = "[email protected]"});
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?
I managed to get this to work:
Expression<Func<User, bool>> expr = user => user.EmailAddress == "[email protected]";
_mockUserRepository.Setup(c => c.GetSingle(It.Is<Expression<Func<User, bool>>>(criteria => criteria == expr)))
.Returns(new User { EmailAddress = "[email protected]" });
User result = _mockUserRepository.Object.GetSingle(expr);
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 = "[email protected]" });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With