Receive emails in Java Selenium tests

Receive emails in Java test suites using MailSlurp, Junit, and Selenium.

With JUnit, MailSlurp and Selenium we can test email sign-up processes using real emails. We can generate test email accounts on demand and receive emails directly within tests. The following is an example on testing user authentication flows using the MailSlurp Authentication Playground site.

We use Selenium to load the playground and 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. If this all works our playground will display a happy dog:

welcome

Setup Gradle project

There are official packages for using Selenium with JUnit. There is also an official Java library for MailSlurp that let's you send and receive emails in Java applications and tests. Let's add these as dependencies to a demo build.gradle.

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:5.1.0'
}

Configure Selenium

Next let's configure Selenium to use Firefox in our tests.

package com.mailslurp.examples.config;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class SeleniumConfig {

    private WebDriver driver;

    static {
        System.setProperty("webdriver.gecko.driver", System.getenv("GECKO_DRIVER"));
    }

    public SeleniumConfig() {
        Capabilities capabilities = DesiredCapabilities.firefox();
        driver = new FirefoxDriver(capabilities);
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    public WebDriver getDriver() {
        return driver;
    }
}

Configure MailSlurp

Next let's configure a MailSlurp Client to use our API Key to connect to the MailSlurp API. This will let us generate real email addresses on demand for testing the sign-up process.

package com.mailslurp.examples.config;

import com.mailslurp.api.api.CommonOperationsApi;
import com.mailslurp.client.ApiClient;
import com.mailslurp.client.Configuration;
import com.mailslurp.client.auth.ApiKeyAuth;

public class MailSlurpConfig {

    public CommonOperationsApi getClient(String apiKey) {
        // configure MailSlurp http client
        ApiClient defaultClient = Configuration
                .getDefaultApiClient()
                .setConnectTimeout(60000);

        // set MailSlurp API Key
        ((ApiKeyAuth) defaultClient.getAuthentication("API_KEY")).setApiKey(apiKey);

        // create instance of common API operations
        return new CommonOperationsApi(defaultClient);
    }
}

Write a test

Lastly let's write a test that does the following:

  • Loads the playground
  • Generate a test email address
  • Sign's up with the address
  • Receive the welcome email
  • Extracts the verification code
  • Enters the code in the playground to confirm the user
  • Logs in

That's quite a lot of functionality! Here is a test that demonstrates the flow. Read the comments at each step for an explaination.

package com.mailslurp.examples;

import com.mailslurp.api.api.CommonOperationsApi;
import com.mailslurp.client.ApiException;
import com.mailslurp.examples.config.MailSlurpConfig;
import com.mailslurp.examples.config.SeleniumConfig;
import com.mailslurp.models.Email;
import com.mailslurp.models.Inbox;
import java.time.Instant;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

@RunWith(BlockJUnit4ClassRunner.class)
public class SeleniumIntegrationTest {

    private final static Pattern VERIFICATION_CODE_PATTERN = Pattern.compile(".*verification code is (\\d+).*");
    private final static String API_KEY = System.getenv("API_KEY");
    private final static String WEBSITE_URL = System.getenv("WEBSITE_URL");

    private static SeleniumConfig config;
    private static WebDriver driver;
    private static CommonOperationsApi mailslurp;
    private static String randomPassword;

    @BeforeClass
    public static void beforeAll() throws ApiException {
        // configure selenium for Firefox
        config = new SeleniumConfig();
        driver = config.getDriver();

        mailslurp = new MailSlurpConfig().getClient(API_KEY);
        randomPassword = "random-" + Instant.now().toEpochMilli();
    }

    @AfterClass
    public static void after() {
        driver.close();
    }

    @Test
    public void canLoadUserSignUpPage() throws ApiException, InterruptedException {
        // visit playground.mailslurp.com to demonstrate testing of user sign-up
        // with an application that requires email verification
        driver.get(WEBSITE_URL);
        assertThat(driver.getTitle(), equalTo("React App"));
        driver.findElement(By.cssSelector("[data-test=sign-in-create-account-link]")).click();

        // create a real, randomized email address with MailSlurp to represent a user
        Inbox inbox = mailslurp.createNewEmailAddress();
        assertThat(inbox.getEmailAddress(), containsString("@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(randomPassword);

        // submit the form to trigger the playgrounds email confirmation process
        driver.findElement(By.cssSelector("[data-test=sign-up-create-account-button]")).click();

        // receive a verification email from playground using mailslurp
        Email email = mailslurp.waitForLatestEmail(inbox.getId(), 60000L);
        assertThat(email.getSubject(), containsString("Please confirm your email address"));

        // extract verification code needed to confirm account
        Matcher matcher = VERIFICATION_CODE_PATTERN.matcher(email.getBody());
        assertThat(matcher.find(), equalTo(true));
        String code = matcher.group(1);
        assertThat(code.length(), equalTo(6));

        // subject verification code to playground page
        driver.findElement(By.name("code")).sendKeys(code);
        driver.findElement(By.cssSelector("[data-test=confirm-sign-up-confirm-button]")).click();

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

        // verify that user can see authenticated content
        // a cute dog and a welcome message
        assertThat(driver.findElement(By.tagName("h1")).getText(), containsString("Welcome"));
    }


    @Test
    public void regexWorks() {
        String subject = "Your Demo verification code is 206354";
        Matcher matcher = VERIFICATION_CODE_PATTERN.matcher(subject);
        assertThat(matcher.find(), equalTo(true));
        assertThat(matcher.group(1), equalTo("" + 206354));
    }
}

To conclude

In summary MailSlurp allows you to send and receive emails in Java test-suites. It works well with JUnit and Selenium to test user sign-up and email verification forms using real email addresses. To get started see the Java documentation.


MailSlurp is free for personal use and scales with your team. Try it today.