5 April 2024 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.
- Connect the Phone or Dongle to the COM Port via USB.
- Utilize a library like
smslib.jar
to pull the SMS containing the OTP. - 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.setInbound(true);
gateway.setOutbound(true);
gateway.setSmscNumber("+91XXXXXXXXXX"); // Replace with the 10-digit mobile number
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
OutboundMessage msg = new OutboundMessage(ExcelConnect.strSMSTo, ExcelConnect.strSMSText);
Service.getInstance().sendMessage(msg);
System.out.println(msg);
System.out.println(ExcelConnect.strSMSTo + "-" + ExcelConnect.strSMSText);
Service.getInstance().stopService();
Service.getInstance().removeGateway(gateway);
}
Solution 2: Automating the SMS Application
For mobile phones, you can automate the SMS application to retrieve the OTP:
- Connect the Android phone or iPhone to your system.
- 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:
- Register for the HTTP SMS Gateway service.
- Use the provided API to fetch the SMS.
- 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.
Conclusion
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.