Interview #76: Selenium Java: How to automate a scenario where you need to check if an email is sent after a user registration?

Interview #76: Selenium Java: How to automate a scenario where you need to check if an email is sent after a user registration?

To automate a test scenario where you need to verify that an email is sent after a user registration using Selenium with Java, you need to break down the process into multiple steps. These steps include user registration, email verification, and validation of the email content. Since Selenium is primarily a web automation tool and does not have built-in email handling capabilities, you will need to integrate additional libraries to check the email.

Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-9606623245

Approach:

Automate User Registration using Selenium

  • Open the registration page.
  • Fill in the required details (e.g., username, email, password, etc.).
  • Submit the form.
  • Capture the confirmation message or UI notification that indicates the registration request is processed.

Check for Email Confirmation

Since Selenium does not handle emails, you can:

  • Use a temporary email service like Mailinator or GuerrillaMail.
  • Access a real email inbox using JavaMail API or IMAP/POP3.
  • Interact with an email testing API like MailSlurp or MailTrap.

Validate Email Content

  • Fetch the latest email.
  • Verify the sender, subject, and email body.
  • If the email contains a confirmation link, extract and interact with it.

Complete the Email Verification (if required)

  • Click on the confirmation link.
  • Verify that the user account is successfully activated.


Implementation Steps in Selenium with Java

Below is an example implementation using Selenium with Java along with the JavaMail API to check for emails.

1. Automate User Registration with Selenium

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class UserRegistrationTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com/register");

        // Fill the registration form
        driver.findElement(By.id("username")).sendKeys("testuser123");
        driver.findElement(By.id("email")).sendKeys("[email protected]");
        driver.findElement(By.id("password")).sendKeys("SecurePassword123");
        driver.findElement(By.id("confirmPassword")).sendKeys("SecurePassword123");
        driver.findElement(By.id("registerButton")).click();

        // Capture and print confirmation message
        WebElement confirmationMessage = driver.findElement(By.id("confirmationMessage"));
        System.out.println("Registration Confirmation: " + confirmationMessage.getText());

        driver.quit();
    }
}        

2. Check for Email Confirmation using JavaMail API

To check the email, you need an email client that supports IMAP/POP3. Below is an example using JavaMail API to read the email.

Maven Dependency for JavaMail API

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>        

Java Code to Fetch Email

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.SubjectTerm;

public class EmailVerification {
    public static void main(String[] args) {
        String host = "imap.gmail.com"; // or "pop.gmail.com" for POP3
        String username = "[email protected]";
        String password = "your-email-password";

        try {
            Properties properties = new Properties();
            properties.put("mail.store.protocol", "imaps");
            properties.put("mail.imaps.host", host);
            properties.put("mail.imaps.port", "993");
            properties.put("mail.imaps.ssl.enable", "true");

            Session session = Session.getInstance(properties);
            Store store = session.getStore("imaps");
            store.connect(username, password);

            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);

            // Search for the registration email
            Message[] messages = inbox.search(new SubjectTerm("Welcome to Example!"));

            if (messages.length > 0) {
                Message email = messages[0];
                System.out.println("Email found: " + email.getSubject());

                // Extract email content
                String emailContent = getEmailContent(email);
                System.out.println("Email Body: " + emailContent);

                // If there's a confirmation link, extract and use it
                String confirmationLink = extractConfirmationLink(emailContent);
                System.out.println("Confirmation Link: " + confirmationLink);
            } else {
                System.out.println("No registration email found.");
            }

            inbox.close(false);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Function to extract email content
    private static String getEmailContent(Message message) throws Exception {
        if (message.isMimeType("text/plain")) {
            return message.getContent().toString();
        } else if (message.isMimeType("multipart/*")) {
            MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
            return mimeMultipart.getBodyPart(0).getContent().toString();
        }
        return "";
    }

    // Function to extract the confirmation link from email body
    private static String extractConfirmationLink(String emailContent) {
        String keyword = "http";
        int startIndex = emailContent.indexOf(keyword);
        if (startIndex != -1) {
            int endIndex = emailContent.indexOf(" ", startIndex);
            return (endIndex == -1) ? emailContent.substring(startIndex) : emailContent.substring(startIndex, endIndex);
        }
        return "No link found";
    }
}        

3. Verify the Email Confirmation Link with Selenium

Once you extract the email verification link, you can automate the email confirmation process.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class EmailConfirmationTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        WebDriver driver = new ChromeDriver();

        // Assume the extracted confirmation link
        String confirmationLink = "https://example.com/confirm?token=abc123";
        driver.get(confirmationLink);

        // Verify account activation
        System.out.println("Account activation page title: " + driver.getTitle());

        driver.quit();
    }
}        

Conclusion

In this automated test case, we:

  1. Used Selenium to register a new user.
  2. Used JavaMail API to access the email and extract the confirmation link.
  3. Used Selenium to open the confirmation link and verify the activation.

This end-to-end flow ensures that the email is sent, received, and contains the expected content, making it a reliable test case for email validation in a web application.


要查看或添加评论,请登录

Software Testing Studio | WhatsApp 91-9606623245的更多文章

社区洞察

其他会员也浏览了