The importance of overriding ToString for tests

Standard behavior of ToString is to print class or structure name. Sometimes if you never need to call tostring for class in application you will avoid to override this basic behavior. Suppose you have this simple structure.

1
2
3
4
public struct Range
{
    public Int32 Left;
    public Int32 Rigth;

This is a simple structure with two field, now I have this test.

1
2
MultiRange res = wcbe.FindHit("thi*", baseText);
Assert.That(res.HitPositions.First().HitRange, Is.EqualTo(new MultiRange.Range(0, 5)));

And when the test fails the output is

1
2
 Expected: RepManagement.Analyzer.Concrete.Auxiliary.MultiRange+Range
  But was:  RepManagement.Analyzer.Concrete.Auxiliary.MultiRange+Range

ouch, since I call for equality with EqualTo, the output is telling me that the objects are not equal, but it does not helps me very much. The best solution is to override the ToString for the Range class making it return some meaningful description.

1
2
3
4
public override string ToString()
{
   return String.Format("Range({0},{1})", Left, Rigth);
}

Overriding ToString in such a basic way is really simple and does not cost you time. Now when the test fails I see

1
2
Expected: Range(0,5)
But was:  Range(0,4)

Now I understand immediately that I have two range object that are not equal, and I can spot immediately the difference.

alk.

Tags: testing