Skip to main content

JUnit email and OTP testing

MailSlurp integrates cleanly with JUnit when the Java test suite owns both the app action and the email assertion. The usual pattern is to create an inbox with the Java SDK, submit the generated address in the workflow under test, wait for the latest email, and extract a code or link from the body.

Install

Maven:

<dependency>
<groupId>com.mailslurp</groupId>
<artifactId>mailslurp-client-java</artifactId>
<version>LATEST</version>
<type>pom</type>
</dependency>

Gradle:

dependencies {
implementation("com.mailslurp:mailslurp-client-java")
}

Create an inbox with the Java SDK

Loading...

Example JUnit OTP flow

import com.mailslurp.apis.InboxControllerApi;
import com.mailslurp.apis.WaitForControllerApi;
import com.mailslurp.clients.ApiClient;
import com.mailslurp.clients.Configuration;
import com.mailslurp.models.Email;
import com.mailslurp.models.InboxDto;
import org.junit.jupiter.api.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.junit.jupiter.api.Assertions.*;

class SignupOtpTest {

@Test
void completesEmailVerification() throws Exception {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setApiKey(System.getenv("API_KEY"));
defaultClient.setConnectTimeout(120_000);
defaultClient.setReadTimeout(120_000);
defaultClient.setWriteTimeout(120_000);

InboxControllerApi inboxControllerApi = new InboxControllerApi(defaultClient);
WaitForControllerApi waitForControllerApi = new WaitForControllerApi(defaultClient);

InboxDto inbox = inboxControllerApi.createInboxWithDefaults().execute();

// Submit inbox.getEmailAddress() in the app under test here.

Email email =
waitForControllerApi
.waitForLatestEmail()
.inboxId(inbox.getId())
.timeout(120_000L)
.unreadOnly(true)
.execute();

Matcher matcher = Pattern
.compile("(?:verification code|OTP|code)[:\\\\s-]*(\\\\d{6})")
.matcher(email.getBody());

assertTrue(matcher.find());
assertNotNull(matcher.group(1));
}
}

Example projects

Loading examples...