Singleton design pattern for Automated Tests
Based on the previous session, we learned about the benefit of ThreadLocal for Parallel Testing and How to apply it to automated test scripts. This will help you decrease the number of drivers defined and used for entire scripts. Save more resources and make your script fast.
On the contrary, with the common resources for the entire system, how to manage them efficiently.?
So how to solve all these problems? The answer is that with each class, there should only be one instance of them in the system (when running the process). The Singleton pattern will help you.
How to implement the Singleton pattern into your script? I’ll guide you step by step when applying the Singleton pattern for GlobalConstants (a class consisting of the global variables for the entire system)
You also apply it for DatabaseConnection, FakerData, ExcelUtilities, or FileUtilities,... Classes should only have one instance)
To apply it, follow the steps below:
After performing these steps, the GlobalConstants will not declare a new instance outside the GlobalConstants. And if you want to get this instance, let’s call the getGlobalConstantsInstance at step 03. At this function, the instance of GlobalConstants will be returned. So, to avoid this instance being null (not existing), the logic to check the existence of this value will be performed before returning.
At this moment, the GlobalConstants look like this:
But inevitable, when performing parallel testing, 2 threads call to this method at the same time and 2 instances are defined. So, how to avoid this situation? In Java programming language, the “synchronized” keyword will help you solve this problem. It only allows one thread to call this method at that moment and this situation never happens.
领英推荐
In this way, the getGlobalConstantsInstance looks like
public static synchronized GlobalConstants getGlobalConstantsInstance() {
if(gConstants == null) {
gConstants = new GlobalConstants();
}
return gConstants;
}
However the synchronized method runs slowly, and the amount of time for running will increase. Instead of setting the synchronized for the method, why do we set it for some statements??
public static GlobalConstants getGlobalConstantsInstance() {
synchronized(GlobalConstants.class){
if(gConstants == null) {
gConstants = new GlobalConstants();
}
}
return gConstants;
}
That’s all steps to apply the Singleton Pattern for your scripts. So, when you want to get the instance, let’s call
Constants.getGlobalConstantsInstance()
From here, you can call the properties or methods you need.
In this way, Singleton Pattern helped you ensure that having one instance of GlobalConstants class for entire scripts and not defined more than one time (especially when you implement scripts for Parallel Testing). Hopefully, you have something new. Thank you and see you in the next session.
References: