Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq - Linq expression in repository - Specify expression in setup

Tags:

c#

linq

mocking

moq

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?

like image 878
Alex Avatar asked Apr 20 '13 19:04

Alex


2 Answers

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);
like image 119
Diana Ionita Avatar answered Sep 22 '22 14:09

Diana Ionita


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]" });
like image 37
Andrew Chaa Avatar answered Sep 20 '22 14:09

Andrew Chaa