使用NUnit 2.5.9,下面的測試意外失敗:處理IEnumerable時NUnit Assert.AreNotEqual的行爲不正確<T>?
[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兩個對象,它只是比較了兩個集合,而忽略其他任何物體上的屬性。
這對我來說是錯誤的:對象實現特定接口的事實並不限制它只執行該角色。或者是.NET中的IEnumerable接口是一種特殊情況?或者我誤解了NUnit?
+1有趣的問題 – sll 2012-02-01 11:57:19