[英]Moq Setup for method with expression<Func<t,bool>> argument
I'm trying to mock the following repository method 我正在尝试模拟以下存储库方法
IEnumerable<T> All(Expression<Func<T, bool>> criteria)
below mock setup works fine 下面的模拟设置工作正常
repository.Setup(repo => repo.All(It.IsAny<Expression<Func<UserLog, bool>>>())).Returns(userLogs);
however, when I want to setup with a specific expression, it does not work. 但是,当我想设置一个特定的表达式时,它不起作用。 When called, method "All" doesn't return the userlogs object as specified. 调用时,方法“全部”不会返回指定的userlogs对象。
repository.Setup(repo => repo.All(v=>v.UserId==userId)).Returns(userLogs);
I've also tried the following. 我也尝试了以下方法。 I know its ugly but I got curious if it would work, and it did. 我知道它很丑,但是我很好奇它是否会起作用,而且确实起作用。
repository.Setup(ulr =>
ulr.All(It.Is<Expression<Func<UserLog, bool>>>(e =>
e.Compile().Invoke(new UserLog { UserId = userId }))))
.Returns(userLogs);
However, weirdly enough, moving that cumbersome expression into a seperate variable and passing it in instead, did not work. 但是,足够奇怪的是,将笨拙的表达式移到一个单独的变量中并传递给它,这是行不通的。 like below 像下面
var itis = It.Is<Expression<Func<UserLog, bool>>>(e => e.Compile().Invoke(new UserLog { UserId = userId }));
repository.Setup(ulr => ulr.All(itis)).Returns(userLogs);
The mocked method is being called as follows; 模拟方法的调用如下:
repository.All(u=>u.UserId==userId);
What I want to do is to mock a method for a specific Expression>. 我想做的是模拟特定Expression>的方法。
I can't figure this one out, would love some help. 我想不通,希望得到一些帮助。
Thanks. 谢谢。
Retrieve the passed expression from the mock and apply it to the fake results using linq 从模拟中检索传递的表达式,并使用linq将其应用于假结果
repository
.Setup(_ => _.All(It.IsAny<Expression<Func<UserLog, bool>>>()))
.Returns((Expression<Func<UserLog, bool>> arg) => userLogs.Where(arg.Compile()));
When the mocked member is called with something like this, for example 例如,当用这样的方式调用嘲笑的成员时
var repo = repository.Object;
var result = repo.All(user => user.UserId == userId);
the user => user.UserId == userId
expression passed to the repo will be invoked in the mock setup, assuming userLogs
is of type IEnumerable<UserLog>
假设userLogs
的类型为IEnumerable<UserLog>
, userLogs
在模拟设置中调用传递给user => user.UserId == userId
的user => user.UserId == userId
表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.