Let us learn some rules to write good and clean unit tests
It will be more easy to remember those rules if we follow the below given acronym
F – Fast : Unit tests should be fast and run quickly. If they won’t then we don’t want to run them frequently, then how would we find problems early enough to get rid from them easily. How our code will give a good performance if our unit tests are not willing to run fast.
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 how would we make sure that we are writing an isolated software/code. It can also cause failure for the other dependent tests and making diagnosis difficult.
R – Repeatable : Tests should be repeatable in any environment whether it’s a production environment, QA environment and on developer 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 through a long text or csv file to tell whether the tests pass. We should not have to manually compare two different external text or csv ﬁles to see whether the tests pass. If the tests aren’t self-validating, then failure can become subjective and running the tests can require a long manual evaluation.
T – Timely : The tests need to be written in a timely fashion. Means they should be written just before the production code that makes them pass. If we write after the production code, then we may ﬁnd the production code to be hard to test. And if we find our production code is really hard to test then it could mean lots of thing like our code is not isolated, adaptable and testable.
If 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!