Java TestNG Selenium user sign up testing with real email addresses
Testing user sign up in Java using TestNG and MailSlurp test email accounts
TestNG is a popular Java test framework that can be used with Selenium and MailSlurp to test web applications end to end. In this example we will use MailSlurp test email accounts to test a demo application sign up process end to end using real email addresses.
The full code for the example can be found on GitHub
Demonstration web app
For this example we will use a React App hosting at playground.mailslurp.com. The app has a typical user sign authentication flow:
- user signs up with an email address and password
- a confirmation code is sent to the user by email
- user confirms their account by entering the code
- user logs in and sees a welcome screen.
We will use MailSlurp to create a test email account for the user and sign-up using Selenium. A successful sign-up and login results in a happy dog being displayed to the user.
Scaffolding a TestNG Java test suite
Create a new directory and add the following pom.xml
:
<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>com.mailslurp.examples</groupId>
<artifactId>testng</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.mailslurp</groupId>
<artifactId>mailslurp-client-java</artifactId>
<version>11.5.20</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.1.0</version>
</dependency>
<dependency>
<groupId>ru.stqa.selenium</groupId>
<artifactId>webdriver-factory</artifactId>
<version>4.3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Install the dependencies with mvn install
. This will install TestNG, Selenium, and MailSlurp. MailSlurp is free to use - you just need to an API Key. Get an API Key from the MailSlurp dashboard by creating an account.
Writing tests
Now time to write some tests. Create src/main/java/com.yourpackage
directories. We will use com.mailslurp.examples
for this demo. Then create a test class:
package com.mailslurp.examples;
public class SignUpTestNGExample {}
Configure webdriver and Selenium
Selenium requires a webdriver to run tests in a browser. We will use a Makefile to download a FireFox (Geckodriver) webdriver and pass the location to our tests with an environment variable.
-include ../.env
DRIVER_LOCATION=geckodriver
DRIVER_URL=https://github.com/mozilla/geckodriver/releases/download/v0.26.0/geckodriver-v0.26.0-linux64.tar.gz
$(DRIVER_LOCATION):
curl -s -L "$(DRIVER_URL)" | tar -xz
chmod +x $(DRIVER_LOCATION)
test: $(DRIVER_LOCATION)
API_KEY=$(API_KEY) \
PATH_TO_WEBDRIVER=$(realpath $(DRIVER_LOCATION)) \
mvn install test
Run make geckodriver
to install the driver locally on a linux machine. Next let's set up a @BeforeSuite
method to initialize the driver with selenium.
// website useful for testing, has a real authentication flow
private static final String PLAYGROUND_URL = "https://playground.mailslurp.com";
// get a MailSlurp API Key free at https://app.mailslurp.com
private static final String YOUR_API_KEY = System.getenv("API_KEY");
private static final String WEBDRIVER_PATH = System.getenv("PATH_TO_WEBDRIVER");
private static final String TEST_PASSWORD = "password-" + new Random().nextLong();
private static final Boolean UNREAD_ONLY = true;
private static final Long TIMEOUT_MILLIS = 30000L;
private static Inbox inbox;
private static Email email;
private static String confirmationCode;
private static ApiClient mailslurpClient;
private static WebDriver driver;
@BeforeSuite
public void initTestSuite() {
assertNotNull(YOUR_API_KEY);
assertNotNull(WEBDRIVER_PATH);
// setup mailslurp
mailslurpClient = Configuration.getDefaultApiClient();
mailslurpClient.setApiKey(YOUR_API_KEY);
mailslurpClient.setConnectTimeout(TIMEOUT_MILLIS.intValue());
// setup webdriver (expects geckodriver binary at WEBDRIVER_PATH)
assertTrue(new File(WEBDRIVER_PATH).exists());
System.setProperty("webdriver.gecko.driver", WEBDRIVER_PATH);
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
}
Let's also add an @AfterSuite
method to close the webdriver when finished:
@AfterSuite(alwaysRun = true)
public void tearDown() {
driver.close();
}
Load the playground site in selenium
First step: load the MailSlurp playground app.
@Test
public void test1_canLoadAuthenticationPlayground() {
driver.get(PLAYGROUND_URL);
assertEquals(driver.getTitle(), "React App");
}
Start the sign-up process
Click the sign up button to begin a user sign up.
@Test
public void test2_canClickSignUpButton() {
driver.findElement(By.cssSelector("[data-test=sign-in-create-account-link]")).click();
}
Create a real email address with MailSlurp and use it to start sign-up on the playground
Now we can create a test email address for the user using MailSlurp and sign up with it in the Playground.
@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,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();
}
Use MailSlurp to receive the confirmation email that is sent by playground
You can wait for the confirmation email to arrive for the user by using the WaitForControllerApi methods. We expect the user's email address to receive a confirmation code.
@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"));
}
Extract the confirmation code from email body using regex patterns
We can use a regex pattern to extract the verification code from the email body.
@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);
}
Submit the confirmation code to the playground to confirm the user
Now that we have the confirmation code we can use Selenium to submit the code.
@Test
public void test6_canSubmitVerificationCodeToPlayground() {
driver.findElement(By.name("code")).sendKeys(confirmationCode);
driver.findElement(By.cssSelector("[data-test=confirm-sign-up-confirm-button]")).click();
}
Test sign-in as confirmed user
For the final step sign in using the email address and password that we verified.
@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"));
}
When successful we will see a nice dog.
Conclusion
TestNG is a great framework for testing end-to-end with Selenium and Java. You can use MailSlurp to create real test email accounts. You can test user actions like user sign-up and account verification using real email addresses. Try it out for free today.
Find the full code on example.
Related content
Golang email library
Golang Email Library for sending and receiving emails in Go over SMTP or HTTP/S.
Java email client: send and receive emails and attachments i...
MailSlurp Java SDK for sending and receive email and attachments on the JVM.
Email for testing
Test email accounts for email testing. Alternatives to Mailinator, MailTrap, Mailosaur and more.
How to wait for Selenium to start during Codeception tests
Example tutorial for how to wait until webdriver and Selenium have started during Codeception PHP tests
Email API for email marketing and more
APIs for email marketing and social campaign testing. Send, receive, validate and test emails in code and online.
How to test an email address
Test email accounts for testing email addresses in code or online. Create fake email accounts for testing.
How to start selenium in a background process and wait for i...
Spawn Selenium server process before tests start for easier acceptance testing.
Stripe get all customers list (example)
Stripe get all customers list (example)
Send and receive email in Cypress JS tests with MailSlurp
Test email sign-up. password verification and more with Cypress JS and MailSlurp.
Cypress Email Plugin - Test email accounts in Javascript (an...
Use real email accounts in CypressJS to test user sign-up, email verification, and more.
Golang mail Library (SMTP)
How to send and receive emails in Go (test email addresses).
Email APIs for Java and Kotlin projects
Test email sending and receive emails without a mail server.
Java TestNG Selenium user sign up testing with real email ad...
Testing user sign up in Java using TestNG and MailSlurp test email accounts
Codeception PHP acceptance testing using real email address ...
Write acceptance tests in PHP with real email addresses using Codeception and MailSlurp
PHP Email Test Plugins: send and receive email in PHPUnit (e...
How to send and receive emails in PHPUnit tests.
PyTest email testing
Send and receive email in Pytest Python tests.
Selenium test email plugins: send and receive email in tests...
Receive emails in Java test suites using MailSlurp, Junit, and Selenium.
Receive email in PHP: using MailSlurp to send and receive em...
Test email in PHP using real email addresses
Robotframework Python Testing using real email addresses
Python automation email testing Robotframework plugin
Testing authentication using real email addresses in Ruby wi...
Cucumber example project using Capybara to test user authentication using real email addresses.
Test applications with real emails using Serenity BDD, JBeha...
Email acceptance testing with Serenity and MailSlurp. Test applications with real email addresses.
.NET SpecFlow testing using MailSlurp email accounts and Sel...
How to test .NET authentication and sign-up using real email accounts with MailSlurp and SpecFlow.
Test email accounts with Jest and Puppeteer
Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.
Test Emails in Selenium with DotNet, CSharp and MailSlurp
Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.
Test emails with Cucumber and Ruby
Generate test email accounts with Ruby and Cucumber. Test email sign-up, password verification and more.
Test user sign-up with NodeJS and WebDriver
Test email related processes like sign-up and verification using WDIO WebDriver and MailSlurp.
TestCafe end-to-end MFA testing for user sign-up and email v...
End-to-end testing with MailSlurp, NodeJS, and TestCafe.
How To Test Emails Before You Send
There are many free tools to test emails before sending. This can help prevent spam warnings and increase deliverability...
Testing OTP password link username and password for 2 factor...
Testing OTP password link username and password for 2 factor authentication (2FA)
Test email address
Free test email address for testing emails online with web dashboard or REST API.
Testing email-related functionality with MailSlurp
Use MailSlurp to test email related functionality using real email addresses.
Testing email with Cypress test email accounts
Test email accounts for CypressJS. End-to-end testing with real email addresses using MailSlurp Cypress plugin.
Testing Webhooks
How to test HTTP webhooks using MailSlurp test hooks.
Send SMTP email with Java
How to use Java SMTP client to send email with MailSlurp mail server on the JDK
Testing Email with Cypress JS and MailSlurp
Email testing with Cypress JS