DEV Community

MailSlurp
MailSlurp

Posted on

Testing sign-up with real emails - Selenium Java email API tutorial (with examples)

Selenium is a powerful browser testing framework. This article will show you how to use real email addresses in Selenium tests - no mail server required. These tests can be combined with automated test flows or devops pipelines to test security or application functionality end-to-end.

selenium email example

Many web applications rely on email: for user sign-up, password reset, newsletters, support responses and more.

This presents a challenge for QA testers using Selenium: how do we test email related processes? Well with free test email account APIs like MailSlurp we can create email addresses within tests and control them from code.

Let's see an example.

Example usage

For this example let's write a Selenium test to sign a user up to a dummy web application.

The source code for this example is available on GitHub

The test app

We'll test against playground.mailslurp.com for this example, a simple React application with a user sign-up process.

welcome

Sign up process

The playground allows a user to sign-up with an email address and password. The app then sends them the user an email containing a confirmation code. The user must copy the code and submit it to the app to confirm their account.

Once confirmed the user can access a picture of a dog by logging in!

welcome

We will test this process end to end.

Test process

We use Selenium to load the playground login form in Firefox. Then we use MailSlurp to generate an email address. Then we enter the email address into the sign up form, receive the welcome email with MailSlurp, extract the verification code and confirm the user. We'll go over each step with examples.

First let's setup the project to include Junit, Selenium, and the MailSlurp Java SDK.

Maven setup

If you use maven then create a pom.xml like so:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>java-maven-selenium</artifactId>
    <version>1.0-SNAPSHOT</version>
    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>com.github.mailslurp</groupId>
            <artifactId>mailslurp-client-java</artifactId>
            <version>7.0.11-RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
Enter fullscreen mode Exit fullscreen mode

Gradle setup

Or if you use Gradle create a build.gradle like so:

plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    // jitpack for mailslurp
    maven { url 'https://jitpack.io' }
}

dependencies {
    testCompile 'junit:junit:4.12'
    testCompile 'org.seleniumhq.selenium:selenium-java:3.4.0'

    // mailslurp client
    testCompile 'com.github.mailslurp:mailslurp-client-java:7.0.11-RELEASE'
}
Enter fullscreen mode Exit fullscreen mode

Download WebDriver

Next you need to download webdriver for your platform. We prefer GeckoDriver for automating Firefox but you can use ChromeDriver with Chrome or any other if you prefer.

Configure Selenium

Now we can create a test and configure Selenium and MailSlurp. You need an API Key to use MailSlurp but it is free for personal use. Get an API Key here then create a test like this:

public class ExampleUsageTest {
    private static final String YOUR_API_KEY = "your_mailslurp_api_key_here";

    // set a timeout as fetching emails might take time
    private static final Long TIMEOUT_MILLIS = 30000L;
    private static final String WEBDRIVER_PATH = "/path/to/your/webdriver";

    private static ApiClient mailslurpClient;
    private static WebDriver driver;

    @BeforeClass
    public static void beforeAll() {
        // setup mailslurp
        mailslurpClient = com.mailslurp.client.Configuration.getDefaultApiClient();
        mailslurpClient.setApiKey(YOUR_API_KEY);
        mailslurpClient.setConnectTimeout(TIMEOUT_MILLIS.intValue());

        // setup webdriver
        System.setProperty("webdriver.gecko.driver", WEBDRIVER_PATH);
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    }
}
Enter fullscreen mode Exit fullscreen mode

The test

Now we can write some tests.

Load the application

Let's load the application and assert that the title is as we expect.

private static final String PLAYGROUND_URL = "https://playground.mailslurp.com";

@Test
public void test1_canLoadAuthenticationPlayground() {
    driver.get(PLAYGROUND_URL);
    assertEquals(driver.getTitle(), "React App");
}
Enter fullscreen mode Exit fullscreen mode

To run the test run mvn install test. The result looks like this:

selenium email example

Start sign-up

Now let's click the sign-up button and load the sign-up page.

@Test
public void test2_canClickSignUpButton() {
    driver.findElement(By.cssSelector("[data-test=sign-in-create-account-link]")).click();
}
Enter fullscreen mode Exit fullscreen mode

Create the an email address

Next we will create a new email address using the MailSlurp client.

private static Inbox inbox;

 @Test
public void test3_canCreateEmailAddressAndSignUp() throws ApiException {
    // create a real, randomized email address with MailSlurp to represent a user
    InboxControllerApi inboxControllerApi = new InboxControllerApi(mailslurpClient);
    inbox = inboxControllerApi.createInbox(null,null,null,null, null, null);

    // check the inbox was created
    assertNotNull(inbox.getId());
    assertTrue(inbox.getEmailAddress().contains("@mailslurp.com"));

    // fill the playground app's sign-up form with the MailSlurp
    // email address and a random password
    driver.findElement(By.name("email")).sendKeys(inbox.getEmailAddress());
    driver.findElement(By.name("password")).sendKeys(TEST_PASSWORD);

    // submit the form to trigger the playground's email confirmation process
    // we will need to receive the confirmation email and extract a code
    driver.findElement(By.cssSelector("[data-test=sign-up-create-account-button]")).click();
}
Enter fullscreen mode Exit fullscreen mode

The result should look like this:

selenium email example

Receive confirmation email

Now we can use MailSlurp to receive the confirmation email that is sent by playground.

private static Email email;

@Test
public void test4_canReceiveConfirmationEmail() throws ApiException {
    // receive a verification email from playground using mailslurp
    WaitForControllerApi waitForControllerApi = new WaitForControllerApi(mailslurpClient);
    email = waitForControllerApi.waitForLatestEmail(inbox.getId(), TIMEOUT_MILLIS, UNREAD_ONLY);

    // verify the contents
    assertTrue(email.getSubject().contains("Please confirm your email address"));
}
Enter fullscreen mode Exit fullscreen mode

Then we can extract the confirmation code from email body using regex pattern:

private static String confirmationCode;

@Test
public void test5_canExtractConfirmationCodeFromEmail() {
    // create a regex for matching the code we expect in the email body
    Pattern p = Pattern.compile(".*verification code is (\\d+).*");
    Matcher matcher = p.matcher(email.getBody());

    // find first occurrence and extract
    assertTrue(matcher.find());
    confirmationCode = matcher.group(1);

    assertTrue(confirmationCode.length() == 6);
}
Enter fullscreen mode Exit fullscreen mode

Confirm the user and login

Now that we have the confirmation code we can submit the code to the Playground and then login with a confirmed account.
If successful we can verfiy the welcome message.

/**
 * Submit the confirmation code to the playground to confirm the user
 */
@Test
public void test6_canSubmitVerificationCodeToPlayground() {
    driver.findElement(By.name("code")).sendKeys(confirmationCode);
    driver.findElement(By.cssSelector("[data-test=confirm-sign-up-confirm-button]")).click();
}
Enter fullscreen mode Exit fullscreen mode

confirm user

/**
 * Test sign-in as confirmed user
 */
@Test
public void test7_canLoginWithConfirmedUser() {
    // load the main playground login page
    driver.get(PLAYGROUND_URL);

    // login with now confirmed email address
    driver.findElement(By.name("username")).sendKeys(inbox.getEmailAddress());
    driver.findElement(By.name("password")).sendKeys(TEST_PASSWORD);
    driver.findElement(By.cssSelector("[data-test=sign-in-sign-in-button]")).click();

    // verify that user can see authenticated content
    assertTrue(driver.findElement(By.tagName("h1")).getText().contains("Welcome"));
}

/**
 * After tests close selenium
 */
@AfterClass
public static void afterAll() {
    driver.close();
}
Enter fullscreen mode Exit fullscreen mode

confirm user

Next steps

This article showed how to test email related processes like user sign-up in Selenium with Java and MailSlurp. In this test we used them to create a new test email account with a unique email address. We then used the email address to sign-up a user and receive a confirmation code.

MailSlurp is free for personal use and has bindings for several popular languages. You can use it to create email addresses on demand then send and receive emails and attachments in code. Check it out.

Top comments (0)