Introduction to Unit Testing

Learn why you should start writing unit tests for your program

1. What is Unit Testing?

Unit tests are typically automated tests written and run by software developers to ensure that a section of an application (known as the “unit”) works and behaves as intended.

When performing a unit test, we basically pick a small chunk of functionality from our code and run tests on it to ensure it's performance.

When developing, we are constantly in a process of testing - we write code, check if it does what we want, ensure nothing else is broken in the meantime (either manually or automated). These tests, called unit tests fundamentally perform the following functions -

  • Describe expected behaviour of our program.

  • Lets us know if your program works the way we want it to.

  • Also tells us if we have broken something along the way.

Unit tests focus on small meaningful chunks of fucntionality and are easy to understand.

2. Why Unit Testing?

Okay so, if we have a program which adds three numbers, how do we know if it works? Yes, you're right! We will run the program and check the results. This way, we will know whether it's a pass or a fail. But what we won't know is why it fails (if it ever does)!

At this point unit tests come into our life and make it a lot more easier. With unit tests -

  • The goal is to isolate each part of the program and show that the individual parts are correct and working independently.

  • We find problems early in the development cycle.

  • Code can be impossible or difficult to unit test if poorly written, thus unit testing can force developers to structure functions and objects in better ways.

  • allows the programmer to refactor code or upgrade system libraries at a later date, and make sure the module still works correctly (e.g., in regression testing).

    Regression testing is re-running functional and non-functional tests to ensure previously developed features still perform after a change. If not, it is called a regression.

  • Unit testing provides a sort of living documentation of the system. Developers looking to learn what functionality is provided by a unit, and how to use it, can look at the unit tests to gain a basic understanding of the unit's interface.

3. Conclusion

While unit tests will not catch every error in the program, because it cannot evaluate every execution path in any but the most trivial programs, unit tests will prove to be a boon for for testing independent units. Unit tests by definition only tests the functionality of the unit themselves, therefore it will not catch integration errors or broader system-level errors such as functions performed across multiple units.

We will further learn about unit testing, tools used for unit tests, it’s different types namely Test Driven Development (TDD) and Behavioural Driven Development (BDD).

Until then, Rise and Code!