简体   繁体   中英

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.

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>.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM