Selenium: How to Test a Website’s Sign Up Form With a Random Email Address

In the Selenium beginner series we’ll solve problems that are commonly faced when automating web testing with Selenium. This post will explain how Selenium can be used to automatically test a website’s sign up form using Webdriver’s Java language bindings.

Challenge

The application under test makes sure users cannot sign up more than once with an email address. Because we want to be able to run the sign up test many times, we need to sign up with a unique email address in each test run.

Solution

We’ll implement a method that generates a unique email address every time the automated test case is run, thus making the test case repeatable.

Example code

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.UUID;

public class SignupTest  {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();

        // Open website
        driver.get("http://testsite.usetrace.com");

        // Find the link to registration form
        WebElement link = driver.findElement(By.cssSelector("[data-name='Register']"));

        // Click the link
        link.click();
        
        // Generate a random email
        final String randomEmail = randomEmail();
        
        // Find the email form field
        WebElement email = driver.findElement(By.id("register-email"));
        
        // Type the random email to the form
        email.sendKeys(randomEmail);
        
        // Find the password form field
        WebElement password = driver.findElement(By.id("register-password"));

        // Type a password to the form. This needs not be unique.
        password.sendKeys("John123");
        
        // Submit the sign up form
        password.submit();
        
        // Check the sign up succeeded by checking that the randomized
        // email appears in the website's header bar.
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                WebElement header = d.findElement(By.id("header-login"));
                return header.getText().contains(randomEmail);
            }
        });
        
        //Close the browser
        driver.quit();
    }

    private static String randomEmail() {
        return "random-" + UUID.randomUUID().toString() + "@example.com";
    }
}

view rawSignupTest.java hosted with ❤ by GitHub

How would you solve this?

If you haven’t yet, try out Usetrace – a codeless UI to Selenium.