简体   繁体   中英

Selenium Java variables access

I need to know a way to access variables of a method from a class in other methods or other class.

example below: i have put all locators of a registration page in one method elements() and then i am trying to use the identifiers e1 in the main method of the same class A and in other class B i have created a object reference of Class A and then trying the same. its not working and i need to know the correct way here.

public class test3 {

     public void elements(){

     By e1=By.id("at-i");
     By e2=By.xpath("//td/td[2]");

    }

     public static void main (String args[])
     {

     WebDriver driver=new FirefoxDriver();
     driver.get("http://testwebsite.com");
     WebElement a1=driver.findelement(e1);

     }
    }

    class b{

     public static void main (String args[]) {

         test3 x=new test3();

         Webelement a2=x.driver.findelement(e2);

     }   
}

You can't access variable from another class in other methods or class. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class (also we don't use main method with selenium).

In your case I'd suggest you to learn about TestNG framework.

Variable E1 and E2 have a local scope to elements() method only.

You have to declare the variables globally to access them anywhere withing the Class.

Hint : Declare variables outside elements() method but inside test3 Class.

Check it out. Hope below the code will help you.

package example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class A {
    public static WebDriver driver = new FirefoxDriver();

    public By elements() {
        By e2 = By.xpath("//td/td[2]");
        return e2;
    }

    public static void main(String args[]) {
        A conA = new A();
        driver.get("http://testwebsite.com");
        WebElement a1 = driver.findElement(conA.elements());
        a1.sendKeys("hello");
    }
}

class B1 {
    public static void main(String args[]) {

        A x = new A();

        WebElement b1 = x.driver.findElement(x.elements());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM