public class SampleClass
{
public int X { get; set; }
public override bool Equals(object obj)
{
if (obj == null) return false;
if (obj.GetType() != typeof(SampleClass)) return false;
var s = obj as SampleClass;
return this.X == s.X;
}
}
Tests:
[TestMethod()]
public void EqualsTest()
{
var sc = new SampleClass { X = 1 };
var sc_copy = sc;
var sc2 = new SampleClass { X = 1 };
Assert.IsFalse(sc.Equals(null));
Assert.IsTrue(sc.Equals(sc));
Assert.IsTrue(sc == sc_copy);
Assert.IsFalse(sc == sc2);
Assert.IsTrue(sc.Equals(sc2));
Assert.IsTrue(sc2.Equals(sc));
Assert.IsTrue(sc.Equals(sc_copy));
Assert.AreEqual(sc, sc2);
Assert.AreEqual(sc, sc_copy);
Assert.AreSame(sc, sc_copy);
Assert.AreNotSame(sc, sc2);
Assert.AreNotSame(sc_copy, sc2);
}
Comments
2 responses to “Equals, ==, and MSTest”
So what’s your point? Would it have killed you to write a sentence.
Sometimes the best way to explain what you want to say about a language is via unit tests. I could have copied the msdn documentation on == vs Equals, but instead I chose to write two groups of tests that demonstrate the expected results of == or equals depending on the case.
The first group shows what the operators do. The second case shows how to specify with a unit test where you are testing for reference equality, or some other class defined definition of equality.
For other examples of this style of documentation, see the ruby koans project (http://github.com/edgecase/ruby_koans) that teaches ruby via unit tests. If you prefer to communicate about code via long essays of text, by all means head to msdn.com and enjoy.