需要存根一个以 Func<> 作为参数的函数

Need to Stub a Function that takes a Func<> as a Parameter

我的数据访问层上有一个方法,可以将任何函数作为搜索条件,运行 这针对我们的 Entity Framework 实体。我正在尝试在业务层上使用 Rhino Mocks 创建单元测试,但这会调用 DAL 方法。当我尝试为此搜索方法创建存根时,我似乎无法将其正确设置为 运行。我有以下方法需要存根:

IQueryable<T> AllSearchBy<T>(params Expression<Func<T, bool>>[] search) where T : class;

我似乎无法找到一个通用表达式来使用,例如 Arg.Is.Anything 用于函数,所以我尝试设置自己的表达式。我有以下内容,如果 Id 为 1,我的 _fakeObjs 中的第一个值应该 return,如果 Id 为 0,我应该 return 为 null(两个单独的测试):

myObjId = 1;  // or 0 for returning a null
System.Linq.Expressions.Expression<Func<MyObj, bool>> myFunc = (a => a.Id == objId); 
IRepository repositoryMock = MockRepository.GenerateMock<IRepository>();
repositoryMock.Stub(x => x.AllSearchBy<MyObj>(myFunc)).Return(_fakeObjs.Where(x => x.Id == myObjId));

但是,我收到以下错误。对于应该 return 一个对象(值 = 1)的对象:

Message: Test method
NS.MyApp.Test.ObjTest.SearchById_ReturnsObj threw exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: source

对于应该 return 空值(值 = 0)的那个:

Message: Test method
NS.MyApp.Test.ObjTest.SearchById_ReturnsNull threw exception:
Rhino.Mocks.Exceptions.ExpectationViolationException:
IRepository.AllSearchBy<NS.EF.MyObj>([]); Expected #1, Actual #0.

我需要做什么来设置参数以传递到我存储库中的 AllSearchBy?

在此先感谢您的帮助!!

如果您尝试将以下内容作为参数传递而不是当前的 myFunc:

会怎样
Arg<Expression<Func<MyObj, bool>>[]>.Is.Anything