Working With Reference Types
Learn to use assertions with confidence when working with reference types.
Introduction
NUnit relies on the frequent use of equality assertions. Equality assertions in NUnit include Assert.AreEqual(x, y)
and its fluent equivalent Assert.That(x, Is.EqualTo(y))
. In computer science, the meaning of equality is nuanced. Equality could mean value equality, which means the values contained by two variables are equal. Equality could also mean reference equality, which means two variables refer to the same object in memory. Understanding and appropriately using these different equalities is important since equality assertions are one of the most used assertions in unit testing.
How NUnit asserts the equality
If the actual and expected parameters of an equality assertion are of the value type, the equality assertion works on value equality. If the actual and expected parameters of an equality assertion are of the reference type, the equality assertion works on reference equality (unless the definition of equality for that type is overridden).
NUnit treats reference type equality by looking at the reference type’s Equals
method. Whatever is defined in the reference type’s Equals
method, NUnit will use to evaluate equality. If the reference type does not explicitly define the Equals
method, it means that its definition is inherited from the base class Object
, which defines Equals
as reference equality. For a detailed explanation of the differences between value and reference equality, refer to the appendix for this lesson titled “How to Define Equality Amongst Objects.”
Implications of treating reference types
Given the theory above and before running the following code, answer the quiz below:
Get hands-on with 1400+ tech skills courses.