Tuesday, June 14, 2016

Visual Studio Unit Tests: Assert.AreSame versus Assert.AreEqual

In the posting "Visual Studio: Developing Unit Tests" an overview was given on creating unit tests with Visual Studio. In that posting the Microsoft.VisualStudio.TestTools.UnitTesting namespace's Assert class was reviewed. This is the class that puts the third A in the AAA (Arrange Act Assert) design pattern.

Two methods stuck out within the Assert class because they appear to be equivalent methods: AreSame versus AreEqual. The AreSame method uses each objects Equals method/methods to determine if two objects are the same memory reference. The AreEqual method determines if the objects are equal in value but may not be the same memory reference.

Both AreEqual and AreSame have a method that behaves in an opposite fashion, namely AreNotEqual and AreNotSame. The AreNotSame method asserts if two objects are the same object reference.  The AreNotEqual method asserts if two objects are equal in value.

An example demonstrating AreEqual, AreSame, AreNotEqual  and AreNotSame is as follows:

The example test method above succeeds because each assertion is true.

No comments :

Post a Comment