Explicitly test what you are trying to test

Had a problem today that initially took me by surprise. The problem was that this test passed:

[Test]
public void EmptyBlocksShouldBeEqual() {
    var first = new Block();
    var second = new Block();
    Assert.That(first, Is.EqualTo(second));
}

Why was this a problem? Because Block is a reference type and I had not overridden Equals(Object o), so we should fall back to the default Object.Equals(Object o) method which compares object references. The references are clearly different, so this test should fail.

To figure out why this test passes we need two pieces of information. First we need to know how Block is defined:

public class Block : IEnumerable<FrameParameters>  { /* ... snip ... */ }

Second, we need to know that the NUnit EqualConstraint implementation has specific handling for IEnumerable classes. So when I called Assert.That(first, Is.EqualTo(second));, this was just comparing the values returned via enumerating both Block instances. This really wasn’t what I wanted – I was trying to test the Equals() implementation. Here’s the corrected test:

[Test]
public void EmptyBlocksShouldBeEqual() {
    var first = new Block();
    var second = new Block();
    Assert.That(first.Equals(second));
}

The moral of the story: make sure you explicitly test what you are trying to test. :)

Comments