https://github.com/mailslurp/examples
<?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>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.mailslurp</groupId>
<artifactId>mailslurp-client-java</artifactId>
<version>15.17.33</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
# Email testing
See [examples repository](https://github.com/mailslurp/examples) for source.
-include ../.env
DRIVER_LOCATION=geckodriver
DRIVER_URL=https://github.com/mozilla/geckodriver/releases/download/v0.32.2/geckodriver-v0.32.2-linux64.tar.gz
FIREFOX_LOCATION=firefox/firefox
$(FIREFOX_LOCATION):
wget --content-disposition "https://download.mozilla.org/?product=firefox-latest-ssl&os=linux64&lang=en-US" -O firefox.tar.bz2
bzip2 -d firefox.tar.bz2
tar -xf firefox.tar
$(DRIVER_LOCATION):
curl -s -L "$(DRIVER_URL)" | tar -xz
chmod +x $(DRIVER_LOCATION)
test: $(DRIVER_LOCATION) $(FIREFOX_LOCATION)
API_KEY=$(API_KEY) \
PATH_TO_WEBDRIVER=$(realpath $(DRIVER_LOCATION)) \
PATH_TO_FIREFOX=$(realpath $(FIREFOX_LOCATION)) \
mvn install test
package com.mailslurp.examples;
import com.mailslurp.apis.EmailControllerApi;
import com.mailslurp.apis.InboxControllerApi;
import com.mailslurp.apis.WaitForControllerApi;
import com.mailslurp.clients.ApiClient;
import com.mailslurp.clients.ApiException;
import com.mailslurp.clients.Configuration;
import com.mailslurp.models.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.CapabilityType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.*;
import static org.junit.Assert.*;
public class MoreMethodsTest {
// 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 Long TIMEOUT_MILLIS = 30000L;
private static ApiClient mailslurpClient;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@BeforeClass
public static void beforeAll() {
assertNotNull(YOUR_API_KEY);
// setup mailslurp
mailslurpClient = Configuration.getDefaultApiClient();
mailslurpClient.setApiKey(YOUR_API_KEY);
mailslurpClient.setConnectTimeout(TIMEOUT_MILLIS.intValue());
}
@Test
public void canCreateInboxAndFetch() throws ApiException {
InboxControllerApi inboxControllerApi = new InboxControllerApi(mailslurpClient);
//<gen>java_create_inbox_with_tags_and_names
// use names, description, and tags to identify an inbox
String randomString = String.valueOf(new Random().nextLong());
String customName = "Test inbox " + randomString;
String customDescription = "My custom description " + randomString;
String customTag = "test-inbox-" + randomString;
// create inbox with options so we can find it later
CreateInboxDto options = new CreateInboxDto()
.name(customName)
.description(customDescription)
.tags(Collections.singletonList(customTag));
InboxDto inbox = inboxControllerApi.createInboxWithOptions(options);
//</gen>
assertEquals(inbox.getName(), customName);
assertEquals(inbox.getDescription(), customDescription);
assertEquals(Objects.requireNonNull(inbox.getTags()).get(0), customTag);
//<gen>java_fetch_inbox_by_name
InboxByNameResult inboxByName = inboxControllerApi.getInboxByName(customName);
assertEquals(inboxByName.getInboxId(), inbox.getId());
//</gen>
//<gen>java_fetch_inbox_by_tags
PageInboxProjection inboxSearchResult = inboxControllerApi.searchInboxes(
new SearchInboxesOptions()
.search(customTag)
);
assertEquals(inboxSearchResult.getNumberOfElements(), Integer.valueOf(1));
assertEquals(inboxSearchResult.getContent().get(0).getId(), inbox.getId());
//</gen>
String mySubject = "Test subject " + randomString;
inboxControllerApi.sendEmailAndConfirm(inbox.getId(), new SendEmailOptions()
.to(Collections.singletonList(inbox.getEmailAddress()))
.subject(mySubject)
);
//<gen>java_fetch_email_by_match
WaitForControllerApi waitForControllerApi = new WaitForControllerApi(mailslurpClient);
List<EmailPreview> matchingEmails = waitForControllerApi.waitFor(new WaitForConditions()
.inboxId(inbox.getId())
.timeout(120000L)
.count(1)
.countType(WaitForConditions.CountTypeEnum.ATLEAST)
.unreadOnly(true)
.addMatchesItem(new MatchOption()
.field(MatchOption.FieldEnum.SUBJECT)
.should(MatchOption.ShouldEnum.CONTAIN)
.value("Test subject")
)
);
//</gen>
assertEquals(matchingEmails.size(), 1);
assertEquals(Objects.requireNonNull(matchingEmails).get(0).getFrom(), inbox.getEmailAddress());
//<gen>java_fetch_email_by_search
EmailControllerApi emailController = new EmailControllerApi(mailslurpClient);
PageEmailProjection emailSearch = emailController.searchEmails(
new SearchEmailsOptions()
.searchFilter("Test subject")
);
//</gen>
assertEquals(emailSearch.getNumberOfElements(), Integer.valueOf(1));
assertEquals(Objects.requireNonNull(emailSearch.getContent()).get(0).getFrom(), inbox.getEmailAddress());
UUID emailId = emailSearch.getContent().get(0).getId();
//<gen>java_get_email_by_id
Email email = emailController.getEmail(emailId, false);
assertEquals(email.getSubject(), mySubject);
assertNotNull(email.getBody());
assertNotNull(email.getFrom());
assertNotNull(email.getAttachments());
//</gen>
}
}
package com.mailslurp.examples;
import com.mailslurp.apis.InboxControllerApi;
import com.mailslurp.apis.WaitForControllerApi;
import com.mailslurp.clients.ApiClient;
import com.mailslurp.clients.ApiException;
import com.mailslurp.clients.Configuration;
import com.mailslurp.models.Email;
import com.mailslurp.models.InboxDto;
import java.io.File;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.CapabilityType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Example Selenium test-suite that loads a dummy authentication website
* and tests user sign-up with an email verification process
*
* See https://www.mailslurp.com/examples/ for more information.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ExampleUsageTest {
// 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 FIREFOX_PATH = System.getenv("PATH_TO_FIREFOX");
private static final Boolean UNREAD_ONLY = true;
private static final Long TIMEOUT_MILLIS = 30000L;
private static ApiClient mailslurpClient;
private static WebDriver driver;
private static final String TEST_PASSWORD = "password-" + new Random().nextLong();
private static InboxDto inbox;
private static Email email;
private static String confirmationCode;
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Setup selenium webdriver and MailSlurp client (for fetching emails)
*/
//<gen>selenium_maven_before_all
@BeforeClass
public static void beforeAll() {
assertNotNull(YOUR_API_KEY);
assertNotNull(WEBDRIVER_PATH);
assertNotNull(FIREFOX_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);
FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(true);
profile.setAcceptUntrustedCertificates(true);
FirefoxOptions options = new FirefoxOptions();
// expects firefox binary at FIREFOX_PATH
options.setBinary(FIREFOX_PATH);
options.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
options.setProfile(profile);
options.setAcceptInsecureCerts(true);
driver = new FirefoxDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.of(TIMEOUT_MILLIS, ChronoUnit.MILLIS));
}
//</gen>
/**
* Load the playground site in selenium
*/
@Test
public void test1_canLoadAuthenticationPlayground() {
logger.info("Load playground");
driver.get(PLAYGROUND_URL);
assertEquals(driver.getTitle(), "React App");
}
/**
* Start the sign-up process
*/
@Test
public void test2_canClickSignUpButton() {
logger.info("Click sign up button");
driver.findElement(By.cssSelector("[data-test=sign-in-create-account-link]")).click();
}
//<gen>selenium_maven_inbox
/**
* Create a real email address with MailSlurp and use it to start sign-up on the playground
*/
@Test
public void test3_canCreateEmailAddressAndSignUp() throws ApiException {
logger.info("Create email address");
// create a real, randomized email address with MailSlurp to represent a user
InboxControllerApi inboxControllerApi = new InboxControllerApi(mailslurpClient);
inbox = inboxControllerApi.createInboxWithDefaults();
logger.info("Assert inbox exists");
// check the inbox was created
assertNotNull(inbox.getId());
assertTrue(inbox.getEmailAddress().contains("@mailslurp"));
logger.info("Fill elements");
// 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);
logger.info("Submit sign-up button");
// 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();
}
//</gen>
/**
* Use MailSlurp to receive the confirmation email that is sent by playground
*/
@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, null, null, null, null);
// verify the contents
assertTrue(email.getSubject().contains("Please confirm your email address"));
}
/**
* Extract the confirmation code from email body using regex pattern
*/
@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
*/
@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
*/
@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();
}
}