Maisie Sadler

Logo

Software Engineer working for TrueLayer in London.

View My GitHub Profile

6 October 2021

Test Driven Development 🧪

by Maisie Sadler

I’m a big advocate for Test Driven Development and would highly recommend reading Kent Beck’s TDD by Example book to learn more about it. TDD is more than just testing, it is a process to drive the quality of code.

The main benefit of practicing TDD by the book is scope control.

What is it?

TDD is a practice of taking requirements and writing code that implements those requirements.

The simplest way to explain TDD is the process of Red-Green-Refactor.

Then think of the next test to make the implementation smarter, keep repeating til you can’t think of any more tests.

Following this practice is a change in mindset from thinking about the entities you might need, starting with the models and class structure then writing the tests to starting with the requirements, thinking about then interface you would like to work with and implementing the functionality you require.

Actually implementing the requirements is the easy bit.

The code is usable because the interface was designed first, you only write the code you need and you have a suite of tests describing all the desired behaviour you intended and wanted to keep.

Sign me up

Programmer tests

The tests you write for TDD are different to unit tests

wiki definition of a Unit and Programmer test:

Failure of a UnitTest shall implicate one (1) and only one (1) unit. (A method, class, module, or package.)

Failure of a ProgrammerTest, under TestDrivenDevelopment, implicates only the most recent edit.

With unit tests…

With programmer tests…

Mocking

One of the big differences I have found with the result of unit testing and programmer testing is the approach to mocking.

Mocking can be great - it allows us to isolate tests and avoid calling slow or costly dependencies.

However it can cause issues if

Some smells that you could be over mocking

When should we use mocks?

Mocking dependencies less reduces test refactoring costs

Refactoring

Refactoring is a specific technique based on behaviour preserving transformations. During refactoring the tests should not need to change and the system shouldn’t be broken for more than a few minutes at a time.

More information here.

Summary

Following TDD by the book you get the following benefits

TDD is more than just testing, it is a process to drive the quality of code.

tags: tdd - testing