Tuesday, October 14, 2008

Approve is the new Assert

assertEquals(5, person.age());
assertEquals("jane", person.getName());
Asserts are a great way of checking primitives. However, they get cumbersome when you want to assert an object. Even the above example really is asking for
assertPerson(person, "jane doe, female age 5");
Of course this quickly becomes a nightmare of trying to describe the person object. This is where approvals come in.
Now you can get a test with nicely formatted output

Name : jane doe
Age : 5
Sex : Female

The more complex the object, the greater the task of writing & maintaining the asserts becomes. While approvals always stay the same one line: 
So whether it’s a single object, a tree of objects, a Gui Component, an Html page, a pdf document, an email, etc… if you can output it to a file, you can approve it. Then you can always view that output in whatever manner you wish. So there’s no need to find a fancy way to describe a pdf: just view it in acrobat, and if it’s good approve it.

1 comment:

Thiago Delgado Pinto said...

Maybe i didn't get the point, but...

1) If you want to see details about your object, you can use the debugger. In good RAD tools, the IDE lets you see the state of each attribute just using things like "Object Inspector".

2) If you want to replace a lot of asserts, put them in a separated method that does exactly this. But if you want to check if a object is valid (check its state), add it a method "IsValid":
game.Add( 5 );
game.Add( 4 );
game.Add( 7 );
game.Add( 2 );
AssertTrue( game.IsValid() );

You can still create a "IValidateMySelf" interface so that your objects can inherit from it to make this job generic:

ApproveMe(IValidateMySelf obj)
AssertTrue( obj.IsValid() );


game.Add( 5 );
game.Add( 4 );
game.Add( 7 );
game.Add( 2 );
ApproveMe( game );

Isn't easier ?