Expose methods

We can expose methods in order to reduce duplicated code. We are able to call the method multiple times. This will ensure a better maintainable test code, because we only have to make adjustments and improvements in one particular place.

**Getting ready
**Search for duplicated functionality we use in our tests. For example the ‘login’ functionality. The selenium actions we have to provide to login will look like this:

WebElement emailEl = driver.findElement(By.name("email"));
emailEl.sendKeys("test@test.com");
WebElement passwordEl = driver.findElement(By.name("password"));
passwordEl.sendKeys("1qazxsw2");
WebElement loginForm = driver.findElement(By.name("login"));
loginForm.submit();

 

How to do it…
We can simple wrap the described functionality in a method and we can give it a sensible name. We can create the method like this:

public void login() {
        WebElement emailEl = driver.findElement(By.name("email"));
        emailEl.sendKeys("test@test.com");
        WebElement passwordEl = driver.findElement(By.name("password"));
        passwordEl.sendKeys("1qazxsw2");
        WebElement loginForm = driver.findElement(By.name("login"));
        loginForm.submit();
    }

We can call this function using the following code:

login();

How it works…
We can simple call the method from our test script, once we have to add one item to the cart. The sensible method name tells use directly what the selenium API calls are doing.

There’s more…

Passing parameters through methods
We can pass parameters through methods, just as in normal programming code. The code below will show us how we can login with parameterized email and password.

public void login(String email, String password) {
        WebElement emailEl = driver.findElement(By.name("email"));
        emailEl.sendKeys(email);
        WebElement passwordEl = driver.findElement(By.name("password"));
        passwordEl.sendKeys(password);
        WebElement loginForm = driver.findElement(By.name("login"));
        loginForm.submit();
    }

We can call this function using the following code:

login("test@test.com", "1qazxsw2");

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.