我需要帮助来理解为什么按降序/升序排序时测试会失败,以及修复它的可能选项是什么?
这是失败文本:
Expected sortedColumnEntries to be in descending order, but found {"17_2", "14_8", "14_5", "13_2", "10_8", "8_5", "5_13", "5_6", "3_7", "3_3", "3_3", "2_5, ..."} where item at index 0 is in wrong order.
代码(DDT测试):
var sortedColumnEntries =
customPage.GetValuesForColumn(columnName);
if (customPage.Grid.Header[columnName].IsSortButtonAscending) {
using (new AssertionScope()) {
customPage.Grid.Header[columnName].IsAscending.Should().BeTrue();
sortedColumnEntries.Should().BeInAscendingOrder(StringComparer.InvariantCultureIgnoreCase);
}
} else {
using (new AssertionScope()) {
customPage.Grid.Header[columnName].IsSortButtonDescending.Should().BeTrue();
customPage.Grid.Header[columnName].IsAscending.Should().BeFalse();
sortedColumnEntries.Should().BeInDescendingOrder(StringComparer.InvariantCultureIgnoreCase);
}
}
public IEnumerable <string> GetValuesForColumn(string columnName) {
if (columnName == "Title") {
return GetTitlesOnCurrentGrid();
}
var headers = Grid.Header.HeaderItems.ToList();
var columnHeader = headers.First(x => x.Text == columnName);
var columnIndex = headers.IndexOf(columnHeader);
return Grid.RowItems.Select(i => {
if (columnName == "Tutor" && i.MultipleTeacherRowItem.Visible) {
i.MultipleTeacherRowItem.HoverMouse(isLongHover: true);
return i.MultipleTeacherRowItem.TooltipText;
}
return i[columnIndex].Text;
});
我尝试了 StringComparer 类的几种选项(例如 Ordinal 等),但没有任何帮助。
如果您希望它们像 Windows 文件资源管理器中的文件名一样排序,则
StringComparer
枚举中的任一选项都无法满足您的需要。您需要使用 Win32_Api StrCmpLogicalW
。会的
比较两个 Unicode 字符串。字符串中的数字被视为数字内容而不是文本。此测试不区分大小写。
然后,您可以使用
StrCmpLogicalW
来实现 IComparer<string>
,如下所示:
public class LogicComparer : IComparer<string>
{
[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string x, string y);
public int Compare(string? x, string? y)
{
if(x == null && y == null)
return 0;
if(x == null)
return -1;
if(y == null)
return 1;
return StrCmpLogicalW(x, y);
}
}
然后就OK了:
var entries = new List<string>() { "17_9", "14_8", "14_5", "13_2", "10_8", "8_5", "5_13", "5_6", "3_7", "3_3", "3_3", "2_5"};
entries.Should().BeInDescendingOrder(new LogicComparer());
至于为什么失败信息显示index为0,因为BeInDescendingOrder方法的逻辑是: 步骤1:获得正确的降序:
{"8_5", "5_13", "5_6", "3_7", "3_3", "3_3", "2_5", "17_9", "14_8", "14_5", "13_2", "10_8"}
step2:比较每个元素。 所以,它会发现第一个元素不正确。