gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:52:19 24 4
gpt4 key购买 nike

使用 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/

    24 4 0