Assert.AreEqual如何确定两个通用IEnumebles之间的相等性?

时间:2022-10-22 15:25:49

I have a unit test to check whether a method returns the correct IEnumerable. The method builds the enumerable using yield return. The class that it is an enumerable of is below:

我有一个单元测试来检查方法是否返回正确的IEnumerable。该方法使用yield return构建可枚举。它是可枚举的类如下:

enum TokenType
{
    NUMBER,
    COMMAND,
    ARITHMETIC,
}

internal class Token
{
    public TokenType type { get; set; }
    public string text { get; set; }
    public static bool operator == (Token lh, Token rh) { return (lh.type == rh.type) && (lh.text == rh.text); }
    public static bool operator != (Token lh, Token rh) { return !(lh == rh); }
    public override int GetHashCode()
    {
        return text.GetHashCode() % type.GetHashCode();
    }
    public override bool Equals(object obj)
    {
        return this == (Token)obj;
    }
}

This is the relevant part of the method:

这是该方法的相关部分:

 foreach (var lookup in REGEX_MAPPING)
 {
     if (lookup.re.IsMatch(s))
     {
         yield return new Token { type = lookup.type, text = s };
         break;
     }
 }

If I store the result of this method in actual, make another enumerable expected, and compare them like this...

如果我将此方法的结果存储在实际中,请将其他可枚举的内容存储起来,并将它们比作这样...

  Assert.AreEqual(expected, actual);

..., the assertion fails.

......,断言失败了。

I wrote an extension method for IEnumerable that is similar to Python's zip function (it combines two IEnumerables into a set of pairs) and tried this:

我为IEnumerable编写了一个类似于Python的zip函数的扩展方法(它将两个IEnumerables组合成一组对)并尝试了这个:

foreach(Token[] t in expected.zip(actual))
{
    Assert.AreEqual(t[0], t[1]);
}

It worked! So what is the difference between these two Assert.AreEquals?

有效!那么这两个Assert.AreEquals有什么区别?

4 个解决方案

#1


25  

Assert.AreEqual is going to compare the two objects at hand. IEnumerables are types in and of themselves, and provide a mechanism to iterate over some collection...but they are not actually that collection. Your original comparison compared two IEnumerables, which is a valid comparison...but not what you needed. You needed to compare what the two IEnumerables were intended to enumerate.

Assert.AreEqual将比较手头的两个对象。 IEnumerables本身就是类型,并提供了迭代某些集合的机制......但它们实际上并不是那个集合。你的原始比较比较了两个IEnumerables,这是一个有效的比较...但不是你需要的。您需要比较两个IEnumerables要枚举的内容。

Here is how I compare two enumerables:

以下是我比较两个枚举的方法:

Assert.AreEqual(t1.Count(), t2.Count());

IEnumerator<Token> e1 = t1.GetEnumerator();
IEnumerator<Token> e2 = t2.GetEnumerator();

while (e1.MoveNext() && e2.MoveNext())
{
    Assert.AreEqual(e1.Current, e2.Current);
}

I am not sure whether the above is less code than your .Zip method, but it is about as simple as it gets.

我不确定上面的代码是否比你的.Zip方法少,但它就像它得到的一样简单。

#2


87  

Found it:

找到了:

Assert.IsTrue(expected.SequenceEqual(actual));

#3


48  

Have you considered using the CollectionAssert class instead...considering that it is intended to perform equality checks on collections?

您是否考虑过使用CollectionAssert类...考虑到它是否要对集合执行相等性检查?

Addendum:
If the 'collections' being compared are enumerations, then simply wrapping them with 'new List<T>(enumeration)' is the easiest way to perform the comparison. Constructing a new list causes some overhead of course, but in the context of a unit test this should not matter too much I hope?

附录:如果要比较的'集合'是枚举,那么简单地用'new List (枚举)'包装它们是执行比较的最简单方法。构建一个新列表当然会产生一些开销,但在单元测试的背景下,我希望这不应该太重要吗?

#4


19  

I think the simplest and clearest way to assert the equality you want is a combination of the answer by jerryjvl and comment on his post by MEMark - combine CollectionAssert.AreEqual with extension methods:

我认为断言你想要的平等的最简单和最清晰的方式是jerryjvl的回答和MEMark评论他的帖子的结合 - 将CollectionAssert.AreEqual与扩展方法结合起来:

CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());

This gives richer error information than the SequenceEqual answer suggested by the OP (it will tell you which element was found that was unexpected). For example:

这提供了比OP建议的SequenceEqual答案更丰富的错误信息(它将告诉您发现哪个元素是意外的)。例如:

IEnumerable<string> expected = new List<string> { "a", "b" };
IEnumerable<string> actual   = new List<string> { "a", "c" }; // mismatching second element

CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
// Helpful failure message!
//  CollectionAssert.AreEqual failed. (Element at index 1 do not match.)    

Assert.IsTrue(expected.SequenceEqual(actual));
// Mediocre failure message:
//  Assert.IsTrue failed.   

You'll be really pleased you did it this way if/when your test fails - sometimes you can even know what's wrong without having to break out the debugger - and hey you're doing TDD right, so you write a failing test first, right? ;-)

如果/当你的测试失败时,你会非常高兴你这样做 - 有时你甚至可以知道什么是错的而不必打破调试器 - 嘿,你正在做正确的TDD,所以你先写一个失败的测试,对? ;-)

The error messages get even more helpful if you're using AreEquivalent to test for equivalence (order doesn't matter):

如果您使用AreEquivalent来测试等效性(顺序无关紧要),则错误消息会更有用:

CollectionAssert.AreEquivalent(expected.ToList(), actual.ToList());
// really helpful error message!
//  CollectionAssert.AreEquivalent failed. The expected collection contains 1
//  occurrence(s) of <b>. The actual collection contains 0 occurrence(s).   

#1


25  

Assert.AreEqual is going to compare the two objects at hand. IEnumerables are types in and of themselves, and provide a mechanism to iterate over some collection...but they are not actually that collection. Your original comparison compared two IEnumerables, which is a valid comparison...but not what you needed. You needed to compare what the two IEnumerables were intended to enumerate.

Assert.AreEqual将比较手头的两个对象。 IEnumerables本身就是类型,并提供了迭代某些集合的机制......但它们实际上并不是那个集合。你的原始比较比较了两个IEnumerables,这是一个有效的比较...但不是你需要的。您需要比较两个IEnumerables要枚举的内容。

Here is how I compare two enumerables:

以下是我比较两个枚举的方法:

Assert.AreEqual(t1.Count(), t2.Count());

IEnumerator<Token> e1 = t1.GetEnumerator();
IEnumerator<Token> e2 = t2.GetEnumerator();

while (e1.MoveNext() && e2.MoveNext())
{
    Assert.AreEqual(e1.Current, e2.Current);
}

I am not sure whether the above is less code than your .Zip method, but it is about as simple as it gets.

我不确定上面的代码是否比你的.Zip方法少,但它就像它得到的一样简单。

#2


87  

Found it:

找到了:

Assert.IsTrue(expected.SequenceEqual(actual));

#3


48  

Have you considered using the CollectionAssert class instead...considering that it is intended to perform equality checks on collections?

您是否考虑过使用CollectionAssert类...考虑到它是否要对集合执行相等性检查?

Addendum:
If the 'collections' being compared are enumerations, then simply wrapping them with 'new List<T>(enumeration)' is the easiest way to perform the comparison. Constructing a new list causes some overhead of course, but in the context of a unit test this should not matter too much I hope?

附录:如果要比较的'集合'是枚举,那么简单地用'new List (枚举)'包装它们是执行比较的最简单方法。构建一个新列表当然会产生一些开销,但在单元测试的背景下,我希望这不应该太重要吗?

#4


19  

I think the simplest and clearest way to assert the equality you want is a combination of the answer by jerryjvl and comment on his post by MEMark - combine CollectionAssert.AreEqual with extension methods:

我认为断言你想要的平等的最简单和最清晰的方式是jerryjvl的回答和MEMark评论他的帖子的结合 - 将CollectionAssert.AreEqual与扩展方法结合起来:

CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());

This gives richer error information than the SequenceEqual answer suggested by the OP (it will tell you which element was found that was unexpected). For example:

这提供了比OP建议的SequenceEqual答案更丰富的错误信息(它将告诉您发现哪个元素是意外的)。例如:

IEnumerable<string> expected = new List<string> { "a", "b" };
IEnumerable<string> actual   = new List<string> { "a", "c" }; // mismatching second element

CollectionAssert.AreEqual(expected.ToArray(), actual.ToArray());
// Helpful failure message!
//  CollectionAssert.AreEqual failed. (Element at index 1 do not match.)    

Assert.IsTrue(expected.SequenceEqual(actual));
// Mediocre failure message:
//  Assert.IsTrue failed.   

You'll be really pleased you did it this way if/when your test fails - sometimes you can even know what's wrong without having to break out the debugger - and hey you're doing TDD right, so you write a failing test first, right? ;-)

如果/当你的测试失败时,你会非常高兴你这样做 - 有时你甚至可以知道什么是错的而不必打破调试器 - 嘿,你正在做正确的TDD,所以你先写一个失败的测试,对? ;-)

The error messages get even more helpful if you're using AreEquivalent to test for equivalence (order doesn't matter):

如果您使用AreEquivalent来测试等效性(顺序无关紧要),则错误消息会更有用:

CollectionAssert.AreEquivalent(expected.ToList(), actual.ToList());
// really helpful error message!
//  CollectionAssert.AreEquivalent failed. The expected collection contains 1
//  occurrence(s) of <b>. The actual collection contains 0 occurrence(s).