我为一些单元测试编写了一个辅助方法来断言&#34;集合等价&#34;使用自定义IEqualityComparer<T>
实现:
/// <summary>
/// Known issue: this checks for set-equality, which means that duplicate items will be interpreted as one.
/// </summary>
public static void AssertCollectionsAreEquivalent<T>(ICollection<T> expected, ICollection<T> actual,
IEqualityComparer<T> comparer)
{
T[] commonMembers = expected.Intersect(actual, comparer).ToArray();
T[] missingMembers = expected.Except(actual, comparer).ToArray();
T[] extraMembers = actual.Except(expected, comparer).ToArray();
if (missingMembers.Any() || extraMembers.Any())
{
Assert.Fail("Collections were not equivalent.{0}Common members: {1}{0}Missing members: {2}{0}Extra members: {3}",
Environment.NewLine,
string.Join(", ", commonMembers.Select(t => t.ToString())),
string.Join(", ", missingMembers.Select(t => t.ToString())),
string.Join(", ", extraMembers.Select(t => t.ToString())));
}
}
一路上,允许调用者提供可以提供自定义字符串格式的对象似乎很有帮助,但我没有看到.NET中适合该帐单的接口。我现在最终使用Func<T, string>
:
/// <summary>
/// Known issue: this checks for set-equality, which means that duplicate items will be interpreted as one.
/// </summary>
private static void AssertCollectionsAreEquivalent<T>(ICollection<T> expected, ICollection<T> actual,
IEqualityComparer<T> comparer, Func<T, string> toStringConverter)
{
T[] commonMembers = expected.Intersect(actual, comparer).ToArray();
T[] missingMembers = expected.Except(actual, comparer).ToArray();
T[] extraMembers = actual.Except(expected, comparer).ToArray();
if (missingMembers.Any() || extraMembers.Any())
{
Assert.Fail("Collections were not equivalent.{0}Common members: {1}{0}Missing members: {2}{0}Extra members: {3}",
Environment.NewLine,
string.Join(", ", commonMembers.Select(toStringConverter)),
string.Join(", ", missingMembers.Select(toStringConverter)),
string.Join(", ", extraMembers.Select(toStringConverter)));
}
}
这是一个单元测试套件,它使用通用测试DTO从数据存储中检索项目,但我们对不同的测试场景有不同的相等定义(因此IEqualityComparer<T>
参数)。我知道我可以定义一个自定义界面来做我想要的事情:
public interface IToStringProvider<in T>
{
string ToString(T obj);
}
...但我希望可能有一些现有项目适合该法案。