Automate Mobile OTP Number with Selenium

Hello Friends,

In your testing you might come across the use case where you need to automate OTP number received in your Mobile Phone. As we all know Selenium can interact with Web Application on browsers, then question arises how to read OTP and use in scenarios like User Registration on some mobile app, payment wallet etc. Also, we know that OTP number is not fixed and we cannot rely on same OTP number every-time. But, we still want to test our application for these user registration scenarios with OTP.

In this blog we will discuss about this case and try to automate this manual verification step.

Step1: Create Java Maven Project on eclipse.

Step2: Add Maven dependencies in POM.xml.

<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>com.OTP.test</groupId>
<artifactId>OTPTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>

<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.0.0</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.1.0</version>
<scope>runtime</scope>
</dependency>

</dependencies>

</project>

I have added 3 dependencies here,
[a] Selenium
[b] TestNG
[c] The most important in this scenario, Twilio SDK dependency.

Twilio provides mechanism to create Test Mobile Number and we can then use these mobile phone numbers to automate this kind of scenario.
You can refer detailed documentation in https://www.twilio.com/docs/usage/api

Step3: You need to do user registration on twilio website and on successful registration, it will send you an email to verify.

Step4: On email verification it will ask for your mobile number on which it will send one time password for user verification. This is required only for registration. We will not require this OTP next.

Step5: It will ask few questions like do write code? what is your preferred language? why you want to use Twilio , you can choose just to explore and what you want to do, you can reply send & receive sms.

Step6: It should land you on Twilio project Dashboard. On trial version it will give you around $15.50 as balance. It will also give you account SID and auth token .

Step7: Click on Get a trial number button. On successful number creation you will get success message.


Step8: For the demonstration purpose we will use amazon website.Also, make sure we are using java 1.8 as we are using Java 1.8 features such as Lambda and Stream API expressions.

Step9: The complete Java program is given below:

Sample Java TestNG Test Program


package com.otp.test;

import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.rest.api.v2010.account.Message;

public class OTPTest {

//Replace your Twilio generated Account SID and AuthToken
public static final String ACCOUNTSID = "ACCOUNTSID";
public static final String AUTHTOKEN = "AUTHTOKEN";

@Test
public void testOTPScenario() {

//Selenium Code to open Amazon User Registration Page
System.setProperty("webdriver.chrome.driver", "chromedriver_mac");
WebDriver driver = new ChromeDriver();
driver.get("https://www.amazon.in");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.cssSelector("a#nav-link-accountList>span>span")).click();
driver.findElement(By.linkText("Start here.")).click();
driver.findElement(By.id("ap_customer_name")).sendKeys("testAutomationWizard");
driver.findElement(By.id("auth-country-picker-container")).click();
driver.findElement(By.xpath("//ul[@role='application']//li/a[contains(text(),'United States +1')]")).click();
driver.findElement(By.id("ap_phone_number")).sendKeys("PhoneNumber");
driver.findElement(By.id("ap_password")).sendKeys("automateOTP@555");
driver.findElement(By.id("continue")).click();

//Twilio Code to get OTP using Twilio API
Twilio.init(ACCOUNTSID, AUTHTOKEN);
String smsBodyStr = getMessage();
System.out.println(smsBodyStr);

//Fetching OTP Number String from i/p SMS
String OTPNumberString = smsBodyStr.replaceAll("[^-?0-9]+", " ");
System.out.println("OTP Number is: "+OTPNumberString);
driver.findElement(By.id("auth-pv-enter-code")).sendKeys(OTPNumberString);
}

//This will fetch OTP send to the registered number

public static String getMessage() {
return getMessagesToFetchOTP().filter(m -> m.getDirection().compareTo(Message.Direction.INBOUND) == 0)
.filter(m -> m.getTo().equals("+1PhoneNumber")).map(Message::getBody).findFirst()
.orElseThrow(IllegalStateException::new);
}

private static Stream<Message> getMessagesToFetchOTP() {
ResourceSet<Message> messages = Message.reader(ACCOUNTSID).read();
return StreamSupport.stream(messages.spliterator(), false);
}

}

In the above code replace PhoneNumber with your Test Twilio Number
"ACCOUNTSID" & "AUTHTOKEN" with Twilio generated Account SID and AuthToken

The o/p generated in eclipse console is:

317053 is your Amazon OTP. OTP is confidential. For security reasons, DO NOT share this OTP with anyone.
OTP Number is: 317053 
PASSED: testOTPScenario


I hope you like this blog and it's helpful. Please share your comments. Till then happy Test Automation ..............

Comments

Popular posts from this blog

Cucumber Series Tutorial 2- Make your Automation Data Driven by Parametrising Feature File

Cucumber Series Tutorial 3- Make your Automation Data Driven by Parametrising Feature File with Scenario Outline and Examples keyword.