As software engineers, it is our job to write code that solves problems and to make sure that it solves the problem correctly. Testing helps us to ensure that the software we write behaves the way it was intended to. Unit Testing is the most basic type of testing that can be performed on a piece of code that verifies its correctness for a given set of values.
General Structure of a Unit Test
A Unit Test generally consists of 3 things:
- A unit (a block of code or a function) that needs to be tested
- The inputs to the unit for which it needs to be tested
- The expected output for the given inputs
Let's build a Mini Testing Library
Let us build a small function that can convert temperatures from Fahrenheit to Celcius. Before we start building the function, we can think of a few possible test cases for the function.
- The input of 0 should return an output of -17.77777777777778
- The input of 5 should return an output of -15
- The input of -4 should return an output of -20
This process of building and writing tests before the actual implementation of the functionality is known as Test-Driven Development (TDD).
Looking at the Structure of a Unit Test, let us write some utility functions that can help us abstract the working of the test.
On executing the above code, the following output is produced.
This shows that our conversion function works for just one of the cases and fails for the other two. To fix the function update the function to include a set of parentheses to fix the conversion function.
Re-running the tests gets the following output.
Well, that was easy, right? We built a simple testing library in just a few lines of code that can be used to test any code we write. Although it is far from something that can be used in production, the main idea and structure remain the same. There are a lot of popular and feature-rich testing frameworks like Jest, Mocha, etc. that provide advanced features like a detailed description of failing tests along with the exact line number and stack trace, that is more suitable for use in production environments.