Rules To Write Clean And Good Unit Tests

Let us learn some rules to write good and clean unit tests. It will be more easy to remember these rules if we follow the below-given acronym.

F.I.R.S.T

F - Fast

Unit tests should be fast, i.e., they should run quickly. If they won't, then we don't want to run them frequently because then, we will not be able to find problems early enough to get rid of them easily. And, if so, how will our code give a good performance if our unit tests are not willing to run faster.

I - Independent

Units tests should be independent from other unit tests. One test should not set up the condition for the next test. If our unit tests are dependent on each other, then it would not be possible for us to make sure that we are writing an isolated software/code. It can also cause failure for the other dependent tests, which will eventually make the diagnosis difficult.

R - Repeatable

Tests should be repeatable in any environment whether it's a production environment, QA environment, or on a developer's machine. If our tests aren’t repeatable in any environment, then we’ll always have an excuse for why they fail.

S - Self-Validating

The tests should have a boolean output. Either they pass or fail. We should not have to read a long text or CSV file to tell whether the tests passed or failed. We should not have to manually compare two different external texts or CSV file to see the result. If the tests aren’t self-validating, then failure can become subjective and to running the tests can require a long manual evaluation.

T - Timely

The tests need to be written in a timely fashion. This means that they should be written just before the production code that makes them pass. If we write after the production code, then we may find the production code to be hard to test. And if we find our production code really hard to test, it could mean lots of things, like our code is not isolated, adaptable, and testable.

I am sure you enjoyed this post. I’d be very grateful if you’d help it spread by emailing it to a friend or sharing it on Twitter or Facebook. Thank you!

Next Recommended Reading Quick Tips for writing Clean Code Part-1