Factory Pattern For Test Automation
Fist of all We should know what/Why is a designing pattern (Please refer the link for more understanding — pending ). And we should know What is Factory pattern is and when it is used.
The factory pattern is one of the most used design patterns in Java. This type of design pattern comes under the creational pattern as this pattern provides one of the best ways to create an object.
In the Factory pattern, we create an object without exposing the creation logic to the client and refer to the newly created object is returned to the client using either specified in an interface and implemented by child classes or implemented in a base class and optionally overridden by derived classes (using a common interface).
Why Factory Pattern is -
- The factory class prevents the coupling of the client code.
- Instead of having multiple new MyObject() call, the initialization is kept in one place, satisfying the Don’t Repeat Yourself(DRY) principle.
- The new version of objects can easily be returned from that factory method. The derived classes must satisfy the Liskov Substitution Principle.
- The factory design pattern provides an approach to code for interface rather than implementation.
- The factory pattern provides an abstraction between implementation and client classes through inheritance.
Let us write some code to understand it.
Demonstration — Real-Time
This Example is simple to understand the behavior of factory pattern,
Demonstration — For Testing Purpose
Using a Factory Pattern with Test classes -
Let see how the factory is integrating with our example. Test classes, as the users, should not really care how the drivers are actually created. What it needs is just a WebDriver instance to execute the given test case. So we come up with our own abstract class “DriverManager” which test classes could use to get a driver instance from it and use them in their tests.
Let's see the sample concrete implementation -
By using Factory Pattern, we completely hide the creational logic of the browser/service instances to the test classes. If we get a new requirement to add a new browser, say PhantomJS, should not be a big deal. We just need to create a PhantomJSDriverManager that extends DriverManager.
Hope this article will be of some help, your query please do not hesitate to ask :)