Automating OTP Verification in Selenium WebDriver

Automating OTP Verification in Selenium WebDriver

5 April 2024 Stephan Petzl Leave a comment Tech-Help

When automating web application testing, handling One-Time Passwords (OTPs) can be a challenging task. OTPs are typically used as a security measure during user registration or login processes. In this guide, we’ll explore methods to automate the retrieval and input of OTPs using Selenium WebDriver.

Solution 1: Using a Connected Phone or Dongle

This method involves directly fetching the OTP from a connected device.

  1. Connect the Phone or Dongle to the COM Port via USB.
  2. Utilize a library like smslib.jar to pull the SMS containing the OTP.
  3. Parse the fetched SMS to extract the OTP.

Here’s a sample code snippet to fetch SMS:

public void sendSMS() throws Exception {
    OutboundNotification outboundNotification = new OutboundNotification();
    SerialModemGateway gateway = new SerialModemGateway("modem.com5", "COM5", 9600, "ZTE", "COM5");
    gateway.setSmscNumber("+91XXXXXXXXXX"); // Replace with the 10-digit mobile number
    OutboundMessage msg = new OutboundMessage(ExcelConnect.strSMSTo, ExcelConnect.strSMSText);
    System.out.println(ExcelConnect.strSMSTo + "-" + ExcelConnect.strSMSText);

Solution 2: Automating the SMS Application

For mobile phones, you can automate the SMS application to retrieve the OTP:

  1. Connect the Android phone or iPhone to your system.
  2. Use a mobile automation tool like Appium to automate the SMS app and parse the OTP.

Solution 3: HTTP SMS Gateway

Register for an HTTP SMS Gateway service to receive SMS programmatically:

  1. Register for the HTTP SMS Gateway service.
  2. Use the provided API to fetch the SMS.
  3. Sort the messages by the latest received SMS and parse to get the OTP.

Solution 4: Retrieving OTP from Database

If you’re testing an in-house application with database access, you can directly retrieve the OTP from the database:

  • Access the database where the OTP is stored.
  • Query the database to retrieve the OTP associated with the specific user or session.


Automating OTP verification in Selenium WebDriver can be accomplished through various methods, each with its own set of prerequisites and complexities. Solutions 3 and 4 are often the most efficient, as they don’t rely on SMS receiving platforms. Choose the method that best fits the context and constraints of your testing environment.

Like this article? there’s more where that came from!