Ara*_*and 28 c# reflection lambda expression moq
我使用Moq来创建数据集的模拟.
我创建了一个小助手类,它允许我有一个内存存储而不是数据库,使单元测试变得轻而易举.这样我可以添加和删除我的模拟数据集中的项目,这允许我测试我的插入和删除服务调用.
在模拟的设置过程中,我有一行如下所示
this.Setup(i => i.AcademicCycles).Returns(mockStore.GetList<AcademicCycle>());
Run Code Online (Sandbox Code Playgroud)
我的模拟有很多属性,所以我想使用反射执行此设置步骤.我已经设法Returns通过反射工作的过程的一部分,但我坚持lambda方法Setup.
Setup 需要一个
Expression<Func<GoalsModelUnitOfWork, IQueryable<AcademicCycle>>> 对应于 i => i.AcademicCycles
我想动态创建它.使用反射我有以下内容:
物业名称:"AcademicCycles"
类型 IQueryable<AcademicCycle>
类型 AcademicCycle
我也有ilambda语句中的实例,它是一个GoalsModelUnitOfWork
fer*_*ero 30
动态创建表达式的代码如下:
ParameterExpression parameter = Expression.Parameter(typeof (GoalsModelUnitOfWork), "i");
MemberExpression property = Expression.Property(parameter, "AcademicCycles");
var queryableType = typeof (IQueryable<>).MakeGenericType(typeof (AcademicCycle));
var delegateType = typeof (Func<,>).MakeGenericType(typeof (GoalsModelUnitOfWork), queryableType);
var yourExpression = Expression.Lambda(delegateType, property, parameter);
Run Code Online (Sandbox Code Playgroud)
结果将具有所需的类型,但问题是返回类型Expression.Lambda()是,LambdaExpression并且您不能执行类型转换Expression<Func<...>>以将其作为参数传递给您的设置函数,因为您不知道的泛型类型参数Func.所以你必须Setup通过反射来调用方法:
this.GetType().GetMethod("Setup", yourExpression.GetType()).Invoke(this, yourExpression);
Run Code Online (Sandbox Code Playgroud)