Unit Tests: how to, when having global variables
Imagine you are developing in some legacy application, and have to use global variables. How can you do unit tests, maintaining the use of global variables?
In this post I will provide you some ideas of how you can accomplish that.
Stay with me, and if you can leave a comment, telling me what you do to address this problem.
Static Methods
If you are testing static methods, and don’t have an instance, you could follow these two options that I refer below.
Notice that the first option allows you, not to make changes in the source code.
This could be a good thing.
But the injecting makes also the implementation more flexible.
Declaring the global variable
You could in the unit test declare the global variable.
This way the code under test will stay the same, and doesn’t need to change.
Injecting as optional parameter
If you are testing static methods, and don’t have an instance, you could add a new optional parameter with the variable.
Then you could add the following check at the first line of the static method:
This way, in the unit test you provide the variable, not having the need declare the global.
Instance Methods
In this case you could inject the global variable, using the constructor or a new setter method.
The global variable, now is a new property of the instance, and is responsibility of who instantiates the class to provide that data.
What is your opinion? What do you prefer?
If available, the second option, with instance methods, injecting via constructor or setter methods all the dependencies, is the preferred approach.
This way, later on, all the dependencies could provided without the need to change the implementation.
Of course, ideally you should stop using global variables, but in some code bases this is not an easy task.
As a first step, you could create unit tests to have more insight about the implementation, and iteratively evolve the code base to remove these bad practices.