0

having code like this, with WebElement inside of class

@Test
    public void testTable() {
       WebElement simpleTable = driver.findElement(By.id("items"));

    simpleTable.click();
    }

how can i access webelements from other class to use it insine other class ?

@Test
        public void testTable2() {

         //-?????--
        simpleTable.click();
        }
  • Greetings! This is a basic object-oriented programming question about variable scope. I suggest grabbing a book on basic Java programming, it might help tremendously with your automation efforts. Good luck! – Yamikuronue May 6 '15 at 16:41
3

The best way is to separate out the details of the WebElement and methods to do with clicking on it, into separate classes - keeping a separation between the code which directly interacts with the UI and the code which does the testing logic. This is a design pattern called the Page Object Model, and your code will end up looking a bit like this:

package com.mycompany.myaut.pages
public class HomePage {
    public void activateTable() {
        WebElement simpleTable = driver.findElement(By.id("items"));
        simpleTable.click();
    }
    public void reorderTable() {
        WebElement simpleTableColumnOne = driver.findElement(By.id("column1"));
        simpleTableColumnOne.click();
    }
}

package com.mycompany.myaut.testcases
public class homePageTests {
    @Test
    public void viewingTheSimpleTable {
        homePage HomePage = new HomePage();
        homePage.activateTable();
    }
    @Test
    public void reorderTheSimpleTable {
        homePage HomePage = new HomePage();
        homePage.activateTable();
        homePage.reorderTable();
    }
}

Note that the page objects deal with exactly how you interact with the web elements on the page, and expose those actions with public methods. Each test case can call those methods to perform the actions they need.

PS If you're using Eclipse, you don't need to just rewrite your code to get it arranged this way; instead, you can use the Refactor tools to make it easier and safer, step by step, extracting your test code out into new classes and methods.

Not the answer you're looking for? Browse other questions tagged or ask your own question.