- read

How to write the best unit tests

Dwen 49

How to write the best unit tests

Dwen
Level Up Coding
Published in
7 min read5 hours ago

--

Guidelines for Unit Testing

Photo by Cédric VT on Unsplash

How do you go about writing unit tests? Many people tend to complete all the functional code first and then gradually add tests afterward.

In this approach to test writing, unit tests often find themselves in a rather unenviable position.

By the time you’ve finished writing all the functional code, writing tests seems like a task you have to grudgingly perform to meet a requirement.

More critically, the code you’ve written might represent several days of work, and you may find it challenging to recall all the details involved in crafting that sizable codebase. Consequently, adding tests at this stage doesn’t significantly enhance code quality.

So, when it comes to writing effective unit tests, the practice of adding tests later is generally suboptimal, marginally better than not writing tests at all. To excel in unit testing, it’s advisable to develop code and tests simultaneously.

You might argue that you add tests right after completing the functionality, isn’t that essentially writing code and tests together? The difference lies in the granularity of the approach.

Composing tests for a substantial task is an exceedingly challenging endeavor and a significant factor contributing to the perceived difficulty of writing tests.

The key to excelling in unit testing is to work with a finer granularity; smaller units of work are essential.

I’m not a great programmer; I’m just a good programmer with great habits.

- Kent Beck

Task decomposition is a valuable practice every programmer should possess, even when striving to excel in unit testing.

To write effective unit tests, you should start with task decomposition. Therefore, you need to break down a requirement into numerous, exceedingly small tasks.

The granularity should be so small that each task can be completed in a very short timeframe, for instance, within half an hour.

Only by breaking tasks down into micro-operations can we have the mental bandwidth to contemplate every detail.