10

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

T GetSingle(Expression<Func<T, bool>> criteria);

我试图模拟这样的设置(我意识到这不起作用):

_mockUserRepository = new Mock<IRepository<User>>();
_mockUserRepository.Setup(c => c.GetSingle(x => x.EmailAddress == "a@b.com"))
    .Returns(new User{EmailAddress = "a@b.com"});

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

_mockUserRepository.Setup(c => c.GetSingle(It.IsAny<Expression<Func<User, bool>>>())
    .Returns(new User{EmailAddress = "a@b.com"});

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

有没有办法在设置中指定使用什么表达式?

4

2 回答 2

10

我设法让它工作:

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);
于 2013-04-20T21:57:57.733 回答
5

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" });
于 2013-10-11T14:33:45.180 回答