Write Tests Backwards

JimNewkirk introduced this idea to me. First you write the asserts:

 assertEquals(4, sum.x);
 assertEquals(5, sum.y);

Then you write the code that computes the answers in asserts:

 Point sum= two.translateBy(three);
 assertEquals(5, sum.x);
 assertEquals(5, sum.y);

Then you write the set up:

 Point two= new Point(2, 2);
 Point three= new Point(3, 3);
 Point sum= two.translateBy(three);
 assertEquals(5, sum.x);
 assertEquals(5, sum.y);


I'm having a hard time seeing why this is better than writing the tests "forwards". -- MikeSmith

Have you tried it?

I have. It helps because of how it makes you think. You start with the goal because that is what is most important and then you work backwards. Everything you do proceeds naturally from the goal. Things that don't have anything to do with the goal get left out be default.

This seems the right thing to me, too. The asserts and verifys (if you're doing MockObjects) are the most valuable bit, so think about them first: any boilerplate needed to tweak the fixture is a (necessary) distraction. -- KeithBraithwaite


EditText of this page (last edited May 21, 2003) or FindPage with title or text search