Hi all, in this article I will explain how to write a general Page class to generate all pages by using the power of JAVA Generics. In this way, you can instantiate your page classes by using JAVA Generics in your tests. You can do instantiations (page object creation) in base Page Class (also you can call this class as Page Generator). Before explaining the details, I want to show you our final aim in an example test class. Then, we will elaborate this solution.

Before starting this article, I want to emphasize that we will go on with our JAVA POM example. ūüėČ If you don’t know this, please check this article first.

In this article, I could not go into full details of Java Generics. But I can suggest you a link. You can learn Java Generics from here.

First, I need to create a Page Class it will be our new Base Class and we generate all page classes in this class so we can also call this class as Page Generator.

In above code, at Generics part, we get page classes as a parameter and instantiate them or generate them at return statement by using “this.driver” and “this.wait” parameters. Here is the most critical line:

return pageClass.getDeclaredConstructor(WebDriver.class, WebDriverWait.class).newInstance(this.driver, this.wait);

Now, BasePage class should extend Page class because the new base class is now Page class.

HomePage and LoginPage classes will remain same. I didn’t do any changes.

We should instantiate Page Class in our setup method before the starting of test methods.

And the final changes should be implemented in LoginTests class. We had two test classes in our POM example and I wanted to change the first one by using JAVA Generics. I didn’t¬†explicitly instantiate the Page Classes, I used JAVA Generics to do this. However, I didn’t change the second test’s code so you can notice the difference easily. ūüėČ Here is the test code:

When you run the tests, all of them should be passed. ūüėČ

java generics

That’s all. In this article, I tried to explain you Page Generation concept by using JAVA Generics by modifying our POM example.

You can find the project code here: https://github.com/swtestacademy/POMWithGenerics

Selenium Webdriver Tutorial Series

Thanks.
-Onur