Unit Testing — An approach to write Testable code and Test cases
I’ll be honest, I’ve never written test cases myself until now. And we’re just about starting out with the best practices of implementing test cases in our code. It’s a long way to go, but we’re confident there will be a day when no line of code goes into production without an automated test running and validating the changes before deployment.
Meanwhile, until we get there, we need an approach — a basic framework to guide the developers in our team to write testable code and write test cases as well. Below are my very rudimentary, unpolished thoughts on how we would be going about it.
I’ve described below 3 questions which I think developers must ask themselves while writing code and corresponding test cases:
1. What is the Objective of this Unit?
a. A unit is a small, testable piece of code which typically takes a few inputs and performs 1 single meaningful objective.
b. A very simple function like return the IST timestamp from UTC timestamp might be too small for taking the efforts of writing test cases for it.
c. Hence, a unit must have a single meaningful function or objective.
d. Ideally each unit should only perform one objective — if it is doing 5–6 things then either the code needs to be broken down into smaller, simpler functions or the unit we’ve selected for testing isn’t small enough.
2. What Input do you need to give to this Unit to run it?
Pretty self-explanatory.
3. How do you know this unit has worked properly?
What is the expected outcome once this Unit has been run with the given inputs? It could be:
a. A value or response the function returns
b. Some databases entries getting updated, inserted etc.
These 3 questions are generic and can be applied to any unit. The idea is, whenever code is written, each developer has more or less this same thought process — Objective, Input, Expected Output — to test the code, just that developers don’t always write them down in a structured manner. So this practice of implementing test cases will hopefully make it easier for developers to visualise how they’re going to write their code and how their test cases are going to look like. Writing down answers to these questions will ensure code can be reliably tested, even when the developer has moved on to other work and their code is changed by others.
We’ll be posting our learning and updates on our journey in implementing automated testing, stay tuned.