如何Assert.AreEqual确定两个通用IEnumerables之间的平等? [英] How does Assert.AreEqual determine equality between two generic IEnumerables?

查看:231
本文介绍了如何Assert.AreEqual确定两个通用IEnumerables之间的平等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元测试来检查方法是否返回正确的的IEnumerable 。该方法构建枚举使用收益回报率。这是一个枚举类是如下:

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:

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.

我写了的IEnumerable 扩展方法类似于的 Python中的拉链函数(它结合了两个IEnumerables成一组对),并试图这样的:

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:

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



它的工作!那么究竟是什么这两个 Assert.AreEqual S'

推荐答案

Assert.AreEqual 是要两个对象手头比较。 的IEnumerable 是对自己和类型,并提供了一​​种机制来遍历收集一些...但他们实际上并没有那么集合。您原来的比较比较了两种的IEnumerable s,这是一个有效的比较......而不是你需要的东西。你需要比较的什么两个的IEnumerable 取值旨在枚举

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.

下面是我比较两个可枚举:

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);
}



我不知道以上是否是更少的代码比你的 .ZIP 方法,但它是因为它得到一样简单。

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

这篇关于如何Assert.AreEqual确定两个通用IEnumerables之间的平等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆