Thursday 26 August 2010

Better TDD By Writing Your Asserts First

Writing unit tests with an Arrange, Act, Assert structure definitely helps but the order often seems at odds with the mental process of TDD. Best practice is to write your asserts first. Here's why:

Arrange First?

Arrange-ing first is virtually impossible. You have no idea what to Arrange until you've written the Act or Assert. This is particularly important when Mocking/Stubbing as the Arrange requires knowledge of the implementation which is exactly what you don't have at this point! * see below

Act First?

Act-ing first seems more reasonable but requires something to first be arranged which can lead you down the dark path of arranging first. If there's any uncertainty about the purpose of the test, which there often is, then this can result in wasted effort.

Assert First

Assert-ing first forces you to clarify the purpose of your test early. Have you ever had that paired conversation of "What are we really trying to do here?", well asserting first is having that conversation. Sure you may not be able to write the entire assert standalone but it will help you to drive the rest of the test and implementation with a clearer mind.

* but I do have knowledge of the implementation

Really? For a trivial implementation great! But if you have an existing external dependency then how do you know that this implementation should call it directly? You don't! Sure it will eventually get called but that may not be the concern of the class under test. Switch back to top down design and let the Assert drive out the interface you require the external dependency to have. Then, and only then, either wrap the dependency to make it expose the interface you require or take the well considered decision to use it directly.

Assert first is really helpful for all but the most trivial tests and can help you achieve that holy grail of loosely coupled, highly cohesive code. Try and see if it works for you!

No comments :