Selenium with Java and JUnit 5: email verification tests
A Selenium test that signs up a user has to read the verification email, and that email never reaches the browser. This guide shows Selenium 4 with JUnit 5 and the single-file Java client: each test gets its own address, explicit waits drive the page, and the client fetches the message from AssertInbox. One test types the one-time code; a second follows the magic link.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, with otp, magic_link and links already extracted. Messages are deleted after 24 hours. A unique tag per test is a private inbox, so parallel tests never read each other's mail.
Get an API key and the client file
Get a key in a click at /start. One request creates a key and your private namespace, with no email address or card. The key is shown once, so keep it in your CI secret store and export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page.
Copy the client next to your tests. It needs Java 11 or later and nothing else:
curl -o src/test/java/AssertInbox.java https://assertinbox.com/sdk/AssertInbox.java
Add Selenium and JUnit 5 to your build. With Maven, the two test dependencies are org.seleniumhq.selenium:selenium-java (version 4.x) and org.junit.jupiter:junit-jupiter. Selenium Manager downloads a matching browser driver for Chrome by itself, so no separate driver setup is needed.
The tests
Save this as src/test/java/SignUpEmailTest.java. Replace the URL, the locators and the success text with those of your app; they are placeholders. Every interaction after a page change goes through WebDriverWait, so the test waits for the element it needs instead of sleeping.
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
class SignUpEmailTest {
static final String APP = System.getenv().getOrDefault("APP_URL", "http://localhost:3000");
final AssertInbox inbox = new AssertInbox(System.getenv("ASSERTINBOX_KEY"), System.getenv("ASSERTINBOX_NAMESPACE"));
String tag;
WebDriver driver;
WebDriverWait wait;
@BeforeEach
void setUp() {
tag = inbox.uniqueTag("sel");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
driver = new ChromeDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(15));
}
@AfterEach
void tearDown() {
driver.quit();
inbox.deleteMessages(tag);
}
void submitSignUp() {
driver.get(APP + "/signup");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("email"))).sendKeys(inbox.address(tag));
driver.findElement(By.cssSelector("button[type=submit]")).click();
}
@Test
void signUpWithCode() {
submitSignUp();
AssertInbox.Message mail = inbox.waitFor(tag, Map.of("subject", "verify"));
assertNotNull(mail.otp, "no code in the email: " + mail.subject);
assertTrue(mail.otp.matches("[0-9]{4,8}"), mail.otp);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("code"))).sendKeys(mail.otp);
driver.findElement(By.cssSelector("button[type=submit]")).click();
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.tagName("body"), "Email verified"));
}
@Test
void signUpWithMagicLink() {
submitSignUp();
String link = inbox.waitForLink(tag, Map.of("subject", "verify"));
driver.get(link);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.tagName("body"), "Email verified"));
}
}
Run it with mvn test or gradle test. The tests read the key from the environment, so the same file works locally and in CI.
Explicit waits, not sleeps
Two different waits are involved and they should stay separate. The email wait is a server-side long poll: one HTTP call that returns as soon as the message arrives. The page waits are Selenium's explicit waits, which poll the DOM until a condition is true or the timeout passes. Avoid Thread.sleep and implicit waits for this flow; a fixed sleep is either too short on a slow day or wastes time on every run.
waitFor retries a 408 timeout up to two more times by default, each waiting up to 20 seconds. Pass "retries" and "timeout" in the filter map to change that, for example for a queue that is slow on shared staging.
Parallel runs with JUnit 5
JUnit 5 can run test classes and methods in parallel when junit.jupiter.execution.parallel.enabled=true is set in junit-platform.properties. The tests above are safe for that because each test builds its own tag in setUp, its own driver and its own wait. The namespace is shared by all of them because it belongs to your key. If your app rate-limits sign-ups per source, lower the parallelism rather than reusing addresses.
When the app sends a second email
A "resend code" button sends a new message to the same address. /v1/wait returns the newest message for the tag, which could be the old one. Pass the id of the message you already read as after and the call returns only a newer message:
@Test
void resendSendsANewCode() {
submitSignUp();
AssertInbox.Message first = inbox.waitFor(tag, Map.of("subject", "verify"));
wait.until(ExpectedConditions.elementToBeClickable(By.id("resend"))).click();
AssertInbox.Message second = inbox.waitFor(tag, Map.of("subject", "verify", "after", first.id));
assertTrue(!second.id.equals(first.id));
assertNotNull(second.otp);
}
Add the method to the same class. Filtering by subject also keeps a welcome email or a marketing message from being mistaken for the verification mail.
Troubleshooting
- AssertInboxException with code timeout. The app never sent the email, or sent it to another address. Print
inbox.address(tag)and compare it with your app's logs. - Code unauthorized, status 401. The key is wrong or missing in the environment that runs the tests.
new AssertInboxthrows at once when the key is empty. - HTTP 429. The key used its 2,000 requests for the day.
GET /v1/meshows usage. - IllegalStateException about a missing code. The email has no recognisable code. Read
mail.textand parse it yourself; the full body is always returned. - Stale element errors. Find elements again after the page changes, and wait for visibility before typing.
- Chrome does not start in CI. Add
--no-sandboxand--disable-dev-shm-usageto the options only inside containers that need them.
Next steps
For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.