我有一个与Nsubstitue对象一起使用.NET集合的问题。与NSubstitue代理对象覆盖的C#集合等于
- 我有一个基类,其中我实现equals(对象),的CompareTo函数
- 在测试I创建此基类中的两个精确Nsubstitue对象代理。
- 将对象放入集合后,集合显示这两个对象代理是两个不同的对象。
我不知道可能是什么原因导致了这种行为,以及如何用模型定义集合。
public class KeyTestClass : IKeyTestClass
{
public int Id { get; private set; }
public KeyTestClass()
{
Id = 1;
}
public override int GetHashCode()
{
return Id;
}
public int CompareTo(IKeyTestClass other)
{
return Id - other.Id;
}
public bool Equals(IKeyTestClass other)
{
return Id == other.Id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((KeyTestClass)obj);
}
}
public interface IKeyTestClass : IComparable<IKeyTestClass>, IEquatable<IKeyTestClass>
{
int Id { get; }
}
public class KeyTestClass2 : IKeyTestClass2
{
}
public interface IKeyTestClass2
{
}
[TestClass]
public class ConsistencyRelatedTests
{
[TestMethod]
public void ValidateTestClass()
{
var dic = new Dictionary<IKeyTestClass,List<IKeyTestClass2>>();
// using new equals function defined by Nsubstittue.
var item1 = Substitute.For<IKeyTestClass>();
var item2 = Substitute.For<IKeyTestClass>();
item1.Id.Returns(1);
item2.Id.Returns(1);
Assert.IsTrue(item1.Equals(item2)); //false, not working
dic.Add(item1, new List<IKeyTestClass2>());
dic.Add(item2, new List<IKeyTestClass2>());
// Using real class equals method
var item3 = new KeyTestClass();
var item4 = new KeyTestClass();
Assert.IsTrue(item3.Equals(item4)); //working
dic.Add(item3, new List<IKeyTestClass2>());
dic.Add(item4, new List<IKeyTestClass2>());
}
}
我的直觉是,因为没有对mocks(item1和item2)上的** Equals(IKeyTestClass other)**方法进行设置,它将返回方法的默认值,在这种情况下,该方法为false 。 –