Moq - Linq expression in repository - Specify expression in setup

不羁的心 提交于 2019-12-21 03:58:09

问题


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);


来源:https://stackoverflow.com/questions/16124263/moq-linq-expression-in-repository-specify-expression-in-setup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!