如何使用 Shouldly 正确断言多重排序?

问题描述 投票:0回答:1

假设我有一个简单的数据类。

public class SortMeClass 
{
 public string StringProp { get; set; }
 public int IntProp { get; set; }
}

然后,我收集

SortMeClass
对象的集合,并按
StringProp
升序排序,然后按
IntProp
降序排序。

在我的集合上使用 Shouldly,我如何断言它首先按

StringProp
排序,然后按
IntProp
降序排列?

c# .net unit-testing mstest shouldly
1个回答
0
投票

首先覆盖

Equals
HashCode

public override bool Equals(object obj)
    => Equals(obj as SortMeClass);

public bool Equals(SortMeClass other)
    => other != null &&
    StringProp == other.StringProp &&
    IntProp == other.IntProp;

public override int GetHashCode()
    => HashCode.Combine(StringProp, IntProp);

然后使用

ShouldBe
可以明确控制是否关心顺序

SortMeClass[] data = 
[
    new() { StringProp = "A", IntProp = 2 },
    new() { StringProp = "A", IntProp = 1 },
    new() { StringProp = "C", IntProp = 2 },
    new() { StringProp = "B", IntProp = 2 }
];

var actual = data.OrderBy(x => x.StringProp).ThenBy(x => x.IntProp);

SortMeClass[] expected = [
    new() { StringProp = "A", IntProp = 1 },
    new() { StringProp = "A", IntProp = 2 },
    new() { StringProp = "B", IntProp = 2 },
    new() { StringProp = "C", IntProp = 2 } //Change StringProp to D and see how the assertion fails
];

actual.ShouldBe(expected, ignoreOrder: false);
© www.soinside.com 2019 - 2024. All rights reserved.