I had a problem with using .NET collections with Nsubstitue objects.
- I have a base class where I implement Equals(object), CompareTo function
- In the test I create two exact Nsubstitue object proxy for this base class.
- After I put the object in the collection, the collection shows that these two object proxy are two different objects.
I wonder what could be the reason of this behavior, and how to define the a collection with mockups.
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>());
}
}