如何在参数化测试中通过属性名断言集合排序?
解决参数化测试中动态指定排序属性的断言问题
你通过NUnit的[TestCase]特性传入属性名字符串做参数化测试,代码如下:
[TestCase("customerId")] [TestCase("connectionType")] public void CanSearchClientsOrderedByProperties(string property)
但不知道怎么在FluentAssertions的断言里用这个属性名验证集合升序排列:
searchResponse.Items.Should().BeInAscendingOrder(i => i.{How to use property name here?});
这里提供几种可行的解决方法:
直接使用FluentAssertions的字符串重载(推荐,需确保FluentAssertions版本足够新)
FluentAssertions的BeInAscendingOrder方法原生支持传入属性路径字符串,直接把参数传进去就行:searchResponse.Items.Should().BeInAscendingOrder(property);这个重载还支持嵌套属性,比如传入
"Customer.Name"就能按客户姓名排序验证。通过反射获取属性值
如果无法使用字符串重载,用反射动态获取指定属性的值作为排序依据:searchResponse.Items.Should().BeInAscendingOrder(item => item.GetType().GetProperty(property).GetValue(item));注意:如果属性名拼写错误或目标对象没有该属性,会抛出
NullReferenceException,测试时要确保传入的属性名准确。构建表达式树(性能更优)
反射在大量测试场景下可能有性能损耗,可通过表达式树构建强类型的属性选择器:// 先定义一个辅助方法 private static Expression<Func<T, object>> GetPropertySelector<T>(string propertyName) { var param = Expression.Parameter(typeof(T), "item"); var property = Expression.Property(param, propertyName); var convert = Expression.Convert(property, typeof(object)); return Expression.Lambda<Func<T, object>>(convert, param); } // 在测试方法中使用 var selector = GetPropertySelector<YourItemType>(property); searchResponse.Items.Should().BeInAscendingOrder(selector);替换
YourItemType为searchResponse.Items中元素的实际类型即可。
内容的提问来源于stack exchange,提问作者YMM
相关产品推荐
相关产品推荐

