Unit and Integration Tests Explained

Unit and integration tests are two types of software level tests. Software level tests involve writing additional code to test existing code. The difference between unit and integration tests is what you would test within each individual test; how much of the software you would test within any one test code function.

Software can become very complicated and contain many different elements and components. You could write an application that contains users, permissions, different functionality per user type, a database to store all the information, etc. A unit test would involve writing code to test single components, or small elements, of the software. An integration test would involve testing multiple components of the software when they’re combined, to ensure that when the softwareis connected together it works as intended. An example unit test could be testing a single password validation function, ensuring that only strong passwords pass the validation. Whereas an example of an integration could involve the full registration of a user, using the registration code as well as the database all connected together.

The function below is a simply multiplication function that takes two parameters and returns the multiplication result of those two parameters.

The below code snippet shows another function that could be used to test the multiply function wrote above. The function writes a success message or a failure message based on the result of the function. This is an example of a unit test, not an integration test, as we are testing one unit of code.

The above code uses an if statement to validate the result of the function being tested. Within real software level tests assertions are used. Assertions are similar to the above if statement but they abstract away the if statement part, so we don’t have to worry about writing it. The below code is a refactored version of the above unit test, but it uses an assertion function to validate the result. The assertion function ‘assertEquals’ is not a function included in JavaScript, it is a custom function that we would have to either write ourselves or use a testing library that includes assert functions. The function takes three parameters, the two variables that we want to test are equal to one another and an error statement that is printed if the assertion fails.

This is only one test case, and in reality there would be a lot more software level tests to ensure that different combinations of numbers work. You could also write tests that pass unexpected values, such as strings, to the function and verify that the function does what is expected in this situation.

Leave a Reply