使用Fluent Assertion的ThenBeInAscendingOrder传表达式参数报错求助
问题:Fluent Assertion验证实体列表排序时的表达式异常
我在使用Fluent Assertion库验证查询返回的BgTaskListItemDto实体列表是否符合特定排序时遇到问题,已耗时数小时仍未解决。当前代码如下:
var prop = typeof(BgTaskListItemDto).GetProperty(orderableAttribute); listResponse.Data.Entities .Select(e => prop.GetValue(e)) .Should().BeInDescendingOrder() .And .ThenBeInAscendingOrder( e => Expression.Property( Expression.Constant(object:e, type:typeof(BgTaskListItemDto)), propertyName:nameof(BgTaskListItemDto.Id)));
其中orderableAttribute来自[DataTestMethod],[DataRow(nameof(BgTaskListItemDto.AccountId))]。单独评估表达式:
Expression.Property(Expression.Constant(e, typeof(BgTaskListItemDto)), nameof(BgTaskListItemDto.Id))
或编译该表达式:
var x = Expression.Lambda(Expression.Property(Expression.Constant(e, typeof(BgTaskListItemDto)), nameof(BgTaskListItemDto.Id))).Compile();
都能获取有效的Id值,但将其作为ThenBeInAscendingOrder的参数时,会抛出异常:
System.ArgumentException: Expression <Property(Constant(e, BgTaskDTOs.BgTaskListItemDto), "Id")> cannot be used to select a member. (Parameter 'expression')
请问我忽略了什么?该方法的正确用法是什么?
解决方法
错误原因
你犯了两个关键错误:
- 传递给
ThenBeInAscendingOrder的表达式写法不符合要求:该方法期望的是直接提取对象属性的lambda表达式,而非手动构建Expression.Property的嵌套逻辑,这种写法会导致Fluent Assertion无法解析要选择的成员。 - 提前执行了
Select(e => prop.GetValue(e)),将原实体序列转换成了属性值的集合,此时序列中已丢失原实体上下文,无法再访问Id属性。
正确用法
直接对原实体列表进行排序验证,无需提前转换序列:
var prop = typeof(BgTaskListItemDto).GetProperty(orderableAttribute); listResponse.Data.Entities .Should().BeInDescendingOrder(e => prop.GetValue(e)) .And.ThenBeInAscendingOrder(e => e.Id);
如果需要通用场景下用反射获取Id属性,可改为:
var orderProp = typeof(BgTaskListItemDto).GetProperty(orderableAttribute); var idProp = typeof(BgTaskListItemDto).GetProperty(nameof(BgTaskListItemDto.Id)); listResponse.Data.Entities .Should().BeInDescendingOrder(e => orderProp.GetValue(e)) .And.ThenBeInAscendingOrder(e => idProp.GetValue(e));
补充说明
Fluent Assertion的排序验证方法(BeInAscendingOrder/BeInDescendingOrder/ThenBeInAscendingOrder等)的参数是Func<T, TKey>类型的lambda,作用是从每个元素中提取排序键,而非要求传入表达式树对象。你之前的写法混淆了表达式树的创建逻辑和方法要求的参数类型,导致解析失败。
内容的提问来源于stack exchange,提问作者alexDuty
相关产品推荐
相关产品推荐

