Posted by Garry Shutler in Unit testing
This is a question I’ve been asked at work before and the answer is quite important as it can lead to tests mysteriously failing.
The difference between the two assertions are quite simple. Assert.AreSame checks that they are the exact same object, memory reference and all (in the case of .NET using ReferenceEquals). Assert.AreEqual checks that objectOne.Equals(objectTwo) will return true.
Here’s a simple example of how they will work with a sensible implementation of Equals.
1 public class Example
3 private int variable;
5 public Example(int variable)
7 this.variable = variable;
10 public override bool Equals(object obj)
12 if (obj is Example)
13 return Equals(obj as Example);
15 return base.Equals(obj);
18 private bool Equals(Example obj)
20 return variable == obj.variable;
25 public class Test
28 public void ExampleTest()
30 var one = new Example(1);
31 var two = new Example(1);
32 var three = new Example(2);
33 var four = one;
35 Assert.AreEqual(one, two); // true
36 Assert.AreSame(one, two); // false
37 Assert.AreEqual(two, three); // false
38 Assert.AreSame(two, three); // false
39 Assert.AreEqual(one, four); // true
40 Assert.AreSame(one, four); // true
So long as you have a sensible Equals method that compares the values of the two objects you can follow these rules:
- If two objects are the same, they will be equal
- If two objects are equal, they may not be the same
- If two objects are not equal, they will not be the same
So now you’ll know the answer next time someone asks what the difference between Assert.AreEqual and Assert.AreSame is.