Test Emails in Selenium with DotNet, CSharp and MailSlurp
Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.
Selenium is a common integration test framework popular with C# developers. With the MailSlurp DotNet SDK you can send and receive emails from code and tests.
If you write .NET applications you probably deal with email addresses at some point: for user sign-up, email newsletters, password resets and more. If you want to test this functionality end-to-end you need test email accounts.
MailSlurp is a free API that lets you create email addresses in C# then send and receive emails with them. This article will show you how to test a web applications user sign-up using Nunit, .NET Core 2.1, Selenium and Firefox Gecko Driver.
Example application
For an example of using emails in selenium with .NET we will use a dummy web app hosted at https://playground.mailslurp.com.
This app has a real sign-up process. It lets users sign-up with an email address, then it sends them a confirmation code via email. The user can then submit the confirmation code and confirm their account. Finally the user can sign in and see a welcome screen.
We'll test this process end to end. Full source code available on GitHub.
Writing a test
To test the Playgrounds authentication process with real email addresses lets set up a .NET Core 2.1 project.
MailSlurp's CSharp Package on NuGet supports .Net Core 2.x and 3.x. If You need another target consider the REST API.
Setup
First you need Firefox and the Selenium Gecko Driver. You can install them with choco
or download them manually and add them to your Path.
choco install firefox
choco install selenium-gecko-driver
Add project dependencies
Create a new .NET Core project and add the following dependencies in YourProject.csproj
:
<ItemGroup>
<PackageReference Include="mailslurp" Version="11.5.20" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="nunit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Selenium.WebDriver" Version="3.141.0" />
<PackageReference Include="Selenium.WebDriver.GeckoDriver" Version="0.26.0.1" />
</ItemGroup>
Create test file
Next create an Nunit test:
using System;
using System.Text.RegularExpressions;
using mailslurp.Api;
using mailslurp.Client;
using mailslurp.Model;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
// Example usage for MailSlurp email API plugin
namespace ExampleService.Tests
{
[TestFixture]
public class ExampleTest
{
// tests will go here
}
}
Next we need to configure Selenium. We will add a FirefoxDriver and tell it to start before our tests. Then we'll add a shutdown method after the tests have finished. Put the following inside the ExampleTest
class:
private static IWebDriver _webdriver;
private static Configuration _mailslurpConfig;
// get a MailSlurp API Key free at https://app.mailslurp.com
private static readonly string YourApiKey = "your-api-key-here";
private static readonly long TimeoutMillis = 30_000L;
[SetUpFixture]
public class NunitSetup
{
// runs once before any tests
[OneTimeSetUp]
public void SetUp()
{
// set up the webdriver for selenium
var timeout = TimeSpan.FromMilliseconds(TimeoutMillis);
var service = FirefoxDriverService.CreateDefaultService()
_webdriver = new FirefoxDriver(service, new FirefoxOptions(), timeout);
_webdriver.Manage().Timeouts().ImplicitWait = timeout;
// configure mailslurp with API Key
Assert.NotNull(YourApiKey);
_mailslurpConfig = new Configuration();
_mailslurpConfig.ApiKey.Add("x-api-key", YourApiKey);
}
// runs once after all tests finished
[OneTimeTearDown]
public void Dispose()
{
// close down the browser
_webdriver.Quit();
_webdriver.Dispose();
}
}
Test loading the playground
Now we can write some tests. So let's load the playground app and click the sign-up button:
[Test, Order(1)]
public void CanLoadPlaygroundAppInBrowser_AndClickSignUp()
{
// open the dummy authentication app and assert it is loaded
_webdriver.Navigate().GoToUrl("https://playground.mailslurp.com");
Assert.AreEqual("React App", _webdriver.Title);
// can click the signup button
_webdriver.FindElement(By.CssSelector("[data-test=sign-in-create-account-link]")).Click();
}
Create test email accounts
Next we need to start a user sign-up. We will need a new test email account first. Create one with MailSlurp then use it to fill the sign-up form:
private static Inbox _inbox;
[Test, Order(2)]
public void CanCreateTestEmail_AndStartSignUp()
{
// first create a test email account
var inboxControllerApi = new InboxControllerApi(_mailslurpConfig);
_inbox = inboxControllerApi.CreateInbox();
// inbox has a real email address
var emailAddress = _inbox.EmailAddress;
// next fill out the sign-up form with email address and a password
_webdriver.FindElement(By.Name("email")).SendKeys(emailAddress);
_webdriver.FindElement(By.Name("password")).SendKeys(Password);
// submit form
_webdriver.FindElement(By.CssSelector("[data-test=sign-up-create-account-button]")).Click();
}
If we run the test the result should look like this:
Receive confirmation email
Once the sign-up form is submitted the playground app will send a confirmation code to the email address. We can wait for the email to arrive using MailSlurp.
private static Email _email;
[Test, Order(3)]
public void CanReceiveConfirmationEmail()
{
// now fetch the email that playground sends us
var waitForControllerApi = new WaitForControllerApi(_mailslurpConfig);
_email = waitForControllerApi.WaitForLatestEmail(inboxId: _inbox.Id, timeout: TimeoutMillis, unreadOnly: true);
// verify the contents
Assert.IsTrue(_email.Subject.Contains("Please confirm your email address"));
}
Extract content and confirm
Next let's find the verification code in the email and submit it to the confirmation screen:
private static String _confirmationCode;
[Test, Order(4)]
public void CanExtractConfirmationCode()
{
// we need to get the confirmation code from the email
var rx = new Regex(@".*verification code is (\d{6}).*", RegexOptions.Compiled);
var match = rx.Match(_email.Body);
_confirmationCode = match.Groups[1].Value;
Assert.AreEqual(6, _confirmationCode.Length);
}
[Test, Order(5)]
public void CanConfirmUserWithEmailedCode()
{
// fill the confirm user form with the confirmation code we got from the email
_webdriver.FindElement(By.Name("code")).SendKeys(_confirmationCode);
_webdriver.FindElement(By.CssSelector("[data-test=confirm-sign-up-confirm-button]")).Click();
}
Running the test should look as follows:
Sign in with confirmed user
Finally we can test that a confirmed user can sign in. Load the playground again and sign in.
[Test, Order(6)]
public void CanLoginWithConfirmedUser()
{
// load the main page again
_webdriver.Navigate().GoToUrl("https://playground.mailslurp.com");
// login with email and password (we expect it to work now that we are confirmed)
_webdriver.FindElement(By.Name("username")).SendKeys(_inbox.EmailAddress);
_webdriver.FindElement(By.Name("password")).SendKeys(Password);
_webdriver.FindElement(By.CssSelector("[data-test=sign-in-sign-in-button]")).Click();
// verify that user can see authenticated content
Assert.IsTrue(_webdriver.FindElement(By.TagName("h1")).Text.Contains("Welcome"));
}
The login should look like this:
Once logged in the user will be greeted with a welcome message.
Next steps
Selenium is a powerful testing tool. When combined with test email accounts you can test email related processes end-to-end. MailSlurp is free email API with C# bindings. Check out the documentation to get started.
Related content
CSharp Email API and SMTP library
Receive email in DotNET Core using C# and MailSlurp
Golang email library for sending and reading emails
Golang Email Library for sending and receiving emails in Go over SMTP or HTTP/S.
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
How to fix the any package by glob error in dotnet
Fix .NET installation on Linux for missing dotnet dependencies.
Disposable email accounts for DotNET core 6
Create real throw-away email addresses for testing and development in .NET core. Follow this guide to get started.
DotNET Core Cake Task Runner (CSharp Makefiles for coverlet code coverage and more)
Create cross platform build scripts for DotNET Core in a way similar to Makefiles.
Create a new .NET MVC project starter (with the CLI)
DotNet starter project MVC generation using the command line interface.
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.
Mailinator alternative
Alternatives to Mailinator for test email accounts. Create real email addresses using MailSlurp
How to send an email using Powershell (Windows and cross-platform)
Use Send-MailMessage in Windows Powershell to send emails using an SMTP server or MailSlurp's free email API.
How to start selenium in a background process and wait for it to start
Spawn Selenium server process before tests start for easier acceptance testing.
CypressJS Example
Test email sign-up. password verification and more with Cypress JS and MailSlurp.
CypressJS Email Testing
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).
Java JVM Examples
Test email sending and receive emails without a mail server.
TestNG Selenium Java Example
Testing user sign up in Java using TestNG and MailSlurp test email accounts
Codeception PHP acceptance testing using real email address APIs
Write acceptance tests in PHP with real email addresses using Codeception and MailSlurp
PHP Email Test Plugins: send and receive email in PHPUnit (example code)
How to send and receive emails in PHPUnit tests.
PyTest Email Testing
Send and receive email in Pytest Python tests.
Java, Selenium
Receive emails in Java test suites using MailSlurp, Junit, and Selenium.
Receive email in PHP: using MailSlurp to send and receive emails
Test email in PHP using real email addresses
Python Robot Framework email test
Python automation email testing Robotframework plugin
Testing authentication using real email addresses in Ruby with Capybara, Cucumber, and Selenium
Cucumber example project using Capybara to test user authentication using real email addresses.
Test applications with real emails using Serenity BDD, JBehave and Selenium
Email acceptance testing with Serenity and MailSlurp. Test applications with real email addresses.
Specflow user sign-up testing with MailSlurp accounts
How to test .NET authentication and sign-up using real email accounts with MailSlurp and SpecFlow.
Jest, Puppeteer
Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.
.NET Selenium C#
Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.
Cucumber, Ruby
Generate test email accounts with Ruby and Cucumber. Test email sign-up, password verification and more.
Webdriver, JS, WDIO
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 verification
End-to-end testing with MailSlurp, NodeJS, and TestCafe.
CSharp Email Tutorial
SMTP mailserver testing and usage in CSharp using
Send email with CSharp using SMTP Client and MailSlurp
Create a custom SMTP client and access MailSlurp inboxes from CSharp/DotNET.
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 authentication (2FA)
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.
How to test 2FA OTP login using SMS codes with Playwright
The ultimate guide to testing OAuth one-time-password flows with real SMS MFA. Use Playwright to automate authentication tests with programmable TXT message APIs.
Testing guide
Integration testing with disposable email accounts using CypressJS, Selenium and many other frameworks. Test OTP password login, transactional emails, notifications and more.
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.
CSharp send SMTP email
How to use CSharp SMTP client to send email with MailSlurp mail server
Testing Email with Cypress JS and MailSlurp
Email testing with Cypress JS