0

I am trying to create a java file that will include all the IDs I'll need to call in my selenium with java project, but each time I call one of the values I get the message that it is null.

Cannot read field "username" because "testScenarios.Actions.testStepActions.testIds" is null

my class is:

public Class testIds{
   @FindBy (id="username")
   public WebElement username;
}

and the way i call it in my code is:

public static void iEnterUsername(){
   testIds.username.sendKeys("username");
}

I am sure that I imported the class in the file I am trying to call but I am not entirely sure what I am doing wrong and few searches didn't bear fruit.

Can you please help in what I am doing wrong?

johncitizen
  • 117
  • 1
  • 2
  • 14

1 Answers1

0

You have to understand the concept of static in Java.

A static method is a method that belongs to a class but does not belong to an instance of that class and this method can be called without the instance or object of that class.

Here you are accessing non-static method staticly.

public static void iEnterUsername(){
   testIds.username.sendKeys("username");
}

Also, you are using PageFactory, so you need to use PageFactory. initElements() static method which takes the driver instance of the given class and the class type, and returns a Page Object with its fields fully initialized.

Solution:

Using Static Approach: Bad Approach Not Recommended

You have to create a constructor and pass the driver instance to it, also initializing PageFactory.initElements(driver, this);

public Class testIds{ WebDriver driver;

   public testIds (WebDriver driver){
        this.driver = driver;
        PageFactory.initElements(driver, this);
   }


   @FindBy (id="username")
   public static WebElement username;

}

In Test Class:

public static void iEnterUsername(){
       testIds t = testIds(driver);
       testIds.username.sendKeys("username");
    }

Other Solution: Standard and Correct Approach

public Class testIds{
   WebDriver driver;

   public testIds (WebDriver driver){
        this.driver = driver;
        PageFactory.initElements(driver, this);
   }


   @FindBy (id="username")
   public WebElement username;

   public WebElement getUserName(){
    return username;
  }
}

Test Class:

public static void iEnterUsername(){
   testIds t = testIds(driver);
   testIds.getUserName().sendKeys("username");
}
Abhishek Dhoundiyal
  • 1,359
  • 1
  • 12
  • 19