What is the process for establishing a class within PageObject framework?

As a beginner in Selenium, I am using IntelliJ along with Selenium WebDriver and Junit. My current challenge lies in setting up the TestBase class within the PageObject framework. Below is an excerpt of my TestBase class:

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class TestBase  {

    WebDriver driver;

    public WebDriver getDriver() {
        return driver;
    }

    @Before
    public void testSetUp(){
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dragana\\Desktop\\chromedriver.exe ");

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized", "--disable-cache");
        driver = new ChromeDriver(options);

        driver.navigate().to("http://store.demoqa.com/");
    }
    @After
    public void testTearDown(){
        driver.close();
    }

}

The above code showcases my test class.

package test;

import PageObjectPage.HomePage;
import PageObjectPage.LogInResultPage;
import PageObjectPage.MyAccount;
import TestBaseSetup.TestBase;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.WebDriver;


public class AccountTest extends TestBase {


    protected WebDriver driver;

    public WebDriver getDriver() {
        return driver;
    }

    @Test
    public void shouldLogIn() {

        HomePage onHomePage = new HomePage(driver);
        System.out.println("Step 1 ");
        MyAccount onMyAccount = onHomePage.clickOnMyAccount();
        System.out.println("Step 2");
        LogInResultPage onResultPage = onMyAccount.LogIn().submitForm();
        System.out.println("Step 3");
        wait(2000);
        Assert.assertTrue(onResultPage.getMessage().contains("ERROR"));
    }

    public void wait(int seconds){
        try {
            Thread.sleep(2000);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }
}

This subsection provides details on the various pages within the PageObject architecture:

package PageObjectPage;


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class HomePage {

    private WebDriver driver;

    public HomePage(WebDriver driver){

        this.driver=driver;
    }

   public MyAccount clickOnMyAccount(){
        //Click on My Account
        driver.findElement(By.className("account_icon")).click();

        return new MyAccount(driver);
    }

    public void wait(int seconds){
        try {
            Thread.sleep(2000);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }

}

Details of the MyAccount page are as follows:

package PageObjectPage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;


public class MyAccount {

    protected WebDriver driver;

    public MyAccount(WebDriver driver){

        this.driver = driver;
    }
    public MyAccount LogIn(){
        //Fill in the text box username
        driver.findElement(By.id("log")).sendKeys("Dragana");
        //Fill in the text box password
        driver.findElement(By.id("pwd")).sendKeys("123456");

        return new MyAccount(driver);
    }
    public LogInResultPage submitForm() {
        //Click on button Log in
        driver.findElement(By.id("login")).click();
        return new LogInResultPage();
    }
}

Lastly, we have the LogInResultPage:

package PageObjectPage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;


public class LogInResultPage {

    protected WebDriver driver;

    public LogInResultPage(){
    }
    public String getMessage(){
        //Printing message
        return driver.findElement(By.tagName("p")).getText();

    }

}

Upon running the test, I encountered the following output:

"C:\Program Files\Java\jdk1.8.0_101\bin\java" ...
Starting ChromeDriver 2.25....
Only local connections are allowed.
Dec 05, 2016 3 .... INFO: Attempting bi-dialect session...
Jan 01, 2020 3... 
INFO: Detected dialect: OSS
Step 1 

java.lang.NullPointerException
    at PageObjectPage.HomeP...
Process finished with exit code -1

I am currently facing challenges pinpointing the source of the problem when running this project. Any insights or assistance provided would be greatly appreciated. Thank you.

Answer №1

To effectively utilize PageObjects in your Selenium tests, it's essential to incorporate the use of PageFactory. For instance, when implementing the clickOnMyAccount method in HomePage.java at line 18, you can utilize the following code snippet:

return PageFactory.initElements(getDriver(), SettingsPage.class);

When commencing your test, make sure to initialize the first page in a similar manner:

HomePage onHomePage = PageFactory.initElements(driver, HomePage .class);

Create a PageBase class where all pages (such as Home and Account) extend from. This base class should include the following structure:

protected WebDriver driver;
public PageBase(WebDriver driver){
    this.driver = driver;
}
public WebDriver getDriver() {
    return this.driver;
}

This setup allows you to eliminate redundant private WebDriver declarations within individual pages. Additionally, Pages that extend PageObjects should be initialized as showcased below:

public HomePage(WebDriver driver) {
        super(driver);
}

Answer №2

Below is the TestBase setup class I have created:

package SetupTestBase;

import PageObjectPage.BasePage;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;


public class TestBase {

    WebDriver driver;

    @Before
    public void prepareForTest(){
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dragana\\Desktop\\chromedriver.exe");

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized", "--disable-cache");
        driver = new ChromeDriver(options);

        driver.navigate().to("http://store.demoqa.com/");
    }

    @After
    public void cleanUp(){

        driver.close();
    }

}

This is the BasePage class structure:

package PageObjectPage;

import org.openqa.selenium.WebDriver;

public class BasePage {

    protected WebDriver driver;

    public BasePage (WebDriver driver){
        this.driver = driver;
    }

    public WebDriver getDriver() {
        return this.driver;
    }

    }

Listed below are the classes for different pages in Page Object Model: - HomePage:

package PageObjectPage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;

public class HomePage extends BasePage {

    @FindBy(how = How.CLASS_NAME, using = "account_icon")
    @CacheLookup
    WebElement button_my_accout;

    public HomePage(WebDriver driver){

        super(driver);
    }

   public MyAccount clickOnMyAccount(){
       //Click on My Account
       button_my_accout.click();

       return PageFactory.initElements(getDriver(), MyAccount.class);

    }

}

- MyAccount page:

package PageObjectPage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;


public class MyAccount extends BasePage {

    @FindBy(id = "log")
    @CacheLookup
    WebElement username;

    @FindBy(how = How.ID, using = "pwd")
    @CacheLookup
    WebElement password;

    @FindBy(how = How.ID, using = "login")
    @CacheLookup
    WebElement login_button;


    public MyAccount(WebDriver driver){

        super(driver);
    }

    public MyAccount logIn(){
        //Enter the username
        username.sendKeys("Dragana");
        //Enter the password
        password.sendKeys("123456");

        return new MyAccount(driver);
    }
    public LogInResultPage submitForm() {
        //Click on Login button
        login_button.click();

        return new LogInResultPage(driver);
    }
}

- LogInResultPage:

package PageObjectPage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LogInResultPage extends BasePage{

    public LogInResultPage(WebDriver driver){

        super(driver);
    }
    public String getMessage(){
        //Fetching and returning message
        return driver.findElement(By.tagName("p")).getText();

    }

}

- Test page details:

package test;

import PageObjectPage.HomePage;
import PageObjectPage.LogInResultPage;
import PageObjectPage.MyAccount;
import SetupTestBase.TestBase;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;


public class AccountTest extends TestBase {

    WebDriver driver;

    @Test
    public void shouldLogin() {


        HomePage onHomePage = PageFactory.initElements(driver, HomePage.class);
        System.out.println("Step 1 ");
        MyAccount onMyAccount = onHomePage.clickOnMyAccount();
        System.out.println("Step 2");
        LogInResultPage onResultPage = onMyAccount.logIn().submitForm();
        System.out.println("Step 3");
        wait(2000);
        Assert.assertTrue(onResultPage.getMessage().contains("ERROR"));
    }

    public void wait(int seconds){
        try {
            Thread.sleep(2000);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Above code has encountered a NullPointerException error. Here is the stack trace:

java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
...
Process finished with exit code -1

Answer №3

If you are facing issues in your test script, it could be because the WebDriver has not been initialized. For example, in the 'AccountTest', the driver being used may not have been properly initialized. To troubleshoot this, you can add a debug point to check its value. Alternatively, in the constructor of your 'TestBase' class, you can initialize the WebDriver and then try running the test again. This should resolve the issue.

public TestBase(){
   ChromeOptions options = new ChromeOptions();
   options.addArguments("--start-maximized", "--disable-cache");
   driver = new ChromeDriver(options);
}

Feel free to let me know if this approach helps or if you need further assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to extract the CSS path of a web element using Selenium and Python?

I am working with a collection of elements using find_elements_by_css_selector, and my next task is to extract their css locators. I attempted the following approach: foo.get_property('css_selector') However, it seems to be returning None. ...

Verification of URL with Page Object Model (POM) in Nightwatch

Just diving into Nightwatch and JavaScript in general, I'm having trouble understanding how to validate a URL using the POM pattern. Any help or suggestions would be greatly appreciated! If you have any useful links for me to read through, that would ...

I encountered an error message while running the Appium code mentioned below

An error occurred while running the main thread. The session was not found. Command duration exceeded timeout: 610 milliseconds. Additional information on the environment - version: '2.53.0', revision: '35ae25b', time: '2016-03-15 ...

Having trouble sending an object from a form using Ajax in SpringMVC

How can I send an object to a controller using jQuery's AJAX? I have defined the User object: private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { retur ...

Tips for extracting a number from a div block with xPath

Recently, I started learning about xPath and encountered a challenging task. I need to extract the text "22 973 ₴" from this code snippet. Can anyone advise me on how to achieve this? <div class="col search_price discounted responsive_secondrow ...

What methods does Ofbiz use to manage sessions?

Excuse my ignorance, but I am new to the world of web development. I am currently working on an application called OFBench which utilizes the Selenium library to mimic user browsing behavior on a website. The website is designed using the Ofbiz template w ...

Combine video using ffmpeg (or similar tools) while incorporating additional elements (such as overlays)

I am currently in the process of scraping clips from Twitch and combining them into a single video file. I have successfully managed to scrape Twitch clip links, but I am only able to get 16-20 videos due to the need to scroll with Selenium. While this is ...

Tips for simulating keypresses and clicks using selenium

I'm encountering an issue with my Selenium code not executing the keyPress + click operation correctly. The objective is to navigate to jqueryui.com and select the first 2 li elements on the page. I am currently working with Selenium 2.23 and Firefo ...

Testing your login functionality with RSpec, Capybara, and Selenium

I'm currently working on passing the login test using rspec integration testing. Although I have set up rspec and confirmed that it's functioning properly, the test is not successfully passing. Below is the code snippet: require 'spec_helpe ...

Selenium: optimize speed by not waiting for asynchronous resources

When using Selenium, it waits for asynchronous resource calls before moving on to a new page. For example: <script src="https://apis.google.com/js/platform.js" async defer></script> In cases where a website includes multiple external APIs (s ...

cells set to read-only ... ..

It is essential to include the code What specific data format needs to be entered into an Excel cell, along with an example? The problem involves coding elements and an accompanying image for easy reference. The task at hand requires more than simply using ...

Timing the execution of each step in JUnit

Struggling with a task for the past 2 days that involves running a JUnit test on JMeter. Here's the code snippet: public class LoadTest5 extends TestCase { private WebDriver driver; public LoadTest5(){} public LoadTest5(String testName){ super( ...

The issue with Selenium automation arises when attempting to interact with a popup window

Currently, I am utilizing Selenium 2.x WebDriver to automate a Java project. However, during the automation process, there is an issue when a "pop up window" appears after clicking a submit button on a particular page, causing the automation to halt. Snip ...

Customize the File Download Directory in Selenium Python Using Chromedriver

I need help with saving files to different locations in Python using Chromedriver. Below is the code I am currently using to set Chrome to download files to a specific folder_path without prompting for download location. After successfully downloading on ...

Tips for achieving jQuery form submission with Ajax functionality

Currently in my Java application, I am submitting a form using JQuery. Below is the JSP code snippet: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> ...

Leveraging combobox for dynamic element selection in Selenium C#

It seems like I may be overlooking a fundamental aspect here. Is it feasible to pass a string in this format? My goal is to develop a versatile web scraper that allows the user to specify which element to locate. However, I am encountering an error stating ...

What is the process for locating elements with the listitem role using Selenium?

Having trouble accessing and cycling through a collection of list items on a webpage using Python. The elements to be fetched are defined as follows, with 4 present on the page: <div data-test-component="StencilReactView" role="listitem& ...

Using Selenium to navigate to Google and selecting the Images link, followed by clicking on the first image

Below is the code I'm working with. When I run it: Firefox opens - as expected Navigates to Google.com - as expected Types "Pluralsight logo" in the search box - as expected However, after that, I see the Google.com page with an empty search box. W ...

"Struggling to upload an image using Selenium WebDriver because the element is not visible? Here are

ff.findElementByxpath(//object[@ id='slPlugin2']).click(); The element is not being recognized. Can you also provide guidance on how to upload media through webdriver? <table class="imgTable photoTable" cellspacing="0"> <div id="file ...

Troubleshooting problem with Firefox and Selenium: Firefox remains unresponsive despite being updated

I encountered an issue while running a functional test that involves opening a Firefox browser with Selenium. Despite trying to troubleshoot by updating Selenium and re-installing Firefox, the error message persists. Here's the detailed error message ...