.net - 处理 IEnumerable<T> 时 NUnit Assert.AreNotEqual 的行为不正确?

标签 .net nunit ienumerable

使用 NUnit 2.5.9,以下测试意外失败:

[TestFixture]
public class FooTest
{
    [Test]
    public void Inequality()
    {
        var first = new Foo(new[] { 1 }, 2);
        var second = new Foo(new[] { 1 }, 3);

        Assert.AreNotEqual(first, second);
    }
}

public struct Foo : IEnumerable<int>, IEquatable<Foo>
{
    private readonly IEnumerable<int> values;

    public int Bar { get; private set; }

    public Foo(IEnumerable<int> values, int bar)
        : this()
    {
        this.values = values;
        Bar = bar;
    }

    public IEnumerator<int> GetEnumerator()
    {
        return values.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public bool Equals(Foo other)
    {
        return other.values.SequenceEqual(values) && other.Bar == Bar;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
        {
            return false;
        }
        if (obj.GetType() != typeof(Foo))
        {
            return false;
        }
        return Equals((Foo)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return ((values != null ? values.GetHashCode() : 0) * 397) ^ Bar;
        }
    }

    public static bool operator ==(Foo left, Foo right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(Foo left, Foo right)
    {
        return !left.Equals(right);
    }
}

深入研究 NUnit 代码,发现当 NUnit 遇到两个实现 IEnumerable 的对象时,它只是比较这两个集合并忽略对象上的任何其他属性。

这对我来说是错误的:对象实现特定接口(interface)的事实并不限制它仅执行该角色。还是 .NET 中的 IEnumerable 接口(interface)是一个特例?还是我只是误解了 NUnit?

最佳答案

看起来这是 NUnit 中的一个错误,据我了解它将在 3.0 版本中修复。下面是一些关于实现 IComparer<T> 的可能工作的讨论。 :

  • Equality constraints and IEnumerable confusion
  • NUUnit 错误跟踪器:Use overridden Equals for IEnumerables, Collections, etc.
  • 关于.net - 处理 IEnumerable<T> 时 NUnit Assert.AreNotEqual 的行为不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9095159/

    相关文章:

    xml - Bamboo NUnit 解析器无法从其他文件夹找到测试结果报告

    nunit - 测试夹具继承和忽略的基本测试夹具

    visual-studio - 如何配置 Resharper 使其 "allows"在方法名称中有下划线?

    c# - 在列表<T>中查找findall

    c# - 在 C# 中,如何从一个内存程序集中引用另一个内存程序集中的类型?

    c# - "standard"初始化基于 COM 的库的方法是什么

    c# - 如何自动生成属性值?

    c# - yield IEnumerable 的迭代器问题

    c# - 锁定可枚举可能会导致多重枚举吗?

    c# - 从 C# COM 方法返回对象和内存所有权