TDD and Guard Assertions

In TDD, tests take actions such as Setup, Trigger, and Verify. Each of these pieces must successfully execute in order for the specification to be verified as accurate to the current behavior of the system.

If there is an external dependency, the test can become vulnerable to a failure of that entity. For example, If the system requires the use of an object factory in order to get an instance of a class, then the test will have to use that factory in order to get the instance. If the test is not a specification of the factory, but rather is a specification of a behavior in the entity it builds, nevertheless a defect in the factory could cause the test to abnormally end.

A developer might be tempted to put a conditional into the test code:

if the factory fails,
then abort the test,
else conduct the test as normal.

This would be done to prevent the test suite from crashing due to a null pointer exception. A better way to do this is the use of a guard assertion.

Basically, anything which must be true for a test to continue executing is asserted to be true. In the example, it could be “assertNotNull(x)“.

If false then the test will stop and fail in an orderly manner.

Avoid conditionals, loops, and other complex code in tests!

This is Scott Bain. Visit us at

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.