将变量从一个类传递给另一个类的sendkeys函数

时间:2017-03-06 11:02:53

标签: java selenium selenium-webdriver

我正在读取一个类中excel的数据,并试图传递另一个类的sendkeys函数中的值,但它无法正常工作。它不会将从excel读取的文本输入到文本框中。我已经验证了从excel中正确读取数据。

我使用以下代码。

DataLibrary.java

public class DataLibrary {
    public static WebDriver driver;
    protected static String username;
    protected String password;

    @Test
    public void readData() throws IOException, Exception, Throwable {

        FileInputStream fis = new FileInputStream("./TestData/Data.xlsx");
        Workbook wb = WorkbookFactory.create(fis);
        Sheet sh = wb.getSheet("Data");

        username = sh.getRow(1).getCell(1).getStringCellValue();
        password = sh.getRow(2).getCell(1).getStringCellValue();

    }

}

Login.java

public class Login extends DataLibrary {

    public static WebDriver driver;

    @BeforeMethod

    public void LoginProcess() throws InterruptedException {

        driver = new FirefoxDriver();
        driver.get("URL");
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        // Username in Login Page
        driver.findElement(By.id("_58_loginText")).sendKeys(username);

        // Password in Login Page
        driver.findElement(By.id("_58_password")).sendKeys(password);

        // Click on Sign In Button
        driver.findElement(By.xpath("//button")).click();
        Thread.sleep(2000);

        // Click on Apply Button in Home Page
        driver.findElement(By.id("applyButton")).click();
    }
}

当我在上面的代码中的sendkeys中传递用户名和密码时,它无效。显示没有错误,但它没有在UI中输入文本。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

这是一个非常愚蠢的错误,你把@BeforeMethod放在应该放@Test的位置,反之亦然,所以 LoginProcess 方法在 readData 之前运行方法,所以你得到空值。

如下所述改变它,一切都会奏效。我已经删除了与excel和webdriver相关的代码,但它很容易理解。

public class DataLibrary {
    protected static String username;
    protected String password;

    @BeforeMethod
    public void readData() {
        username = "gaurang";
        password = "shah";
    }
}

然后是你的测试用例

public class Login extends DataLibrary {

    @Test
    public void LoginProcess() throws InterruptedException {
        System.out.println(username);
        System.out.println(password);
    }
}
相关问题