Moq-存储库中的Linq表达式-在设置中指定表达式 [英] Moq - Linq expression in repository - Specify expression in setup

查看:50
本文介绍了Moq-存储库中的Linq表达式-在设置中指定表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的界面上有一个方法如下:

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

我意识到我将错误的参数传递给设置.
阅读此答案后,我可以通过传入Expression使其正常工作,如下所示:

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

但是,这意味着如果我使用任何表达式调用GetSingle方法,都会返回相同的结果.

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?

推荐答案

如果您不介意通用设置,则这样会更简单.

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

这篇关于Moq-存储库中的Linq表达式-在设置中指定表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆