Select Page
Mobile App Testing

How to Automate OTP in Appium – Explained with Code

Find out how to automate OTP in Appium by following just 4 simple steps. We have provided the code you will need and have explained the code for your understanding as well.

How to automate OTP Scenario using Appium

Appium is one of the best mobile app automation tools in the market and knowing how to automate OTP in Appium is a fundamental technique every automation tester must know. If you are wondering why we need to automate OTP in Appium when we can simply have the developer make the OTP static and proceed with our script. There is a big catch in such a method because the above solution will work only for the STAGE or DEV environment. But when it comes to a production environment, we can’t just run the same static OTP automation script over and over again as it’s simply not practical. Being a leading Test Automation Company we always believe in successfully implementing automation that enhances the overall quality. So in this blog, we will be explaining how to automate OTP in Appium by following 4 simple steps.

How to automate OTP in Appium

There are two ways to automate the OTP scenario using Appium in an Android device;

  • We can either make use of our notification bar to retrieve the OTP.
  • Or, we can open up our ‘messages’ app and retrieve the OTP.

In this blog, we will be focusing on how to retrieve the OTP from the notification bar, as it is a less complex approach that keeps the focus of testing on the intended app. Let’s start with the basic prerequisites you need to get the job done.

Pre-Requisite

  • Install the application you work with (Example., Amazon)
  • Connect your mobile (Android) to the PC either through cable or Wi-Fi.
  • Install Appium on your PC.

4 Steps to Automate OTP in Apppium

We have mentioned the code that we have used for this example below. We have also broken down the main parts of the code and explained them one by one so that you will be able to get a crystal-clear understanding of the process. Make sure you don’t skip the specific notes that we have mentioned below the explanations as well. Now let’s find out how to automate OTP in Appium.

Step 1: Open the notification panel and clear the previous notifications
driver.openNotifications();

try {
   AndroidElement notification = driver.findElementById("com.android.systemui:id/clear_notifications");
   
   if (notification.isDisplayed()) {
      notification.click();
      return new EnterPhoneNumber(driver);
   } 

} catch (Exception e) {
   System.out.println(e);
   driver.pressKey(new KeyEvent(AndroidKey.BACK));
}

Code Explanation

  • driver.openNotifications() – Opens Android notifications (Emulator only)
  • AndroidElement notification = driver.findElementById(“com.android.systemui:id/clear_notifications”) – This line will find and store the element in “notification”.
  • if (notification.isDisplayed()) – checks whether the “clear_notification” element is present.
  • notification.click() – if present, clear the notification by clicking on it.
  • driver.pressKey(new KeyEvent(AndroidKey.BACK)) – if no notification is present, then press back to the application.

Note: Kindly change the locator according to your mobile element. We have taken the “clear_notification” locator for the following element.

How to automate OTP in Appium

Step 2: Write the code to the point where you are asked to enter the mobile number.

how to enter otp in appium

Step 3: Once you have entered the mobile number, open the notification panel and wait for the OTP to appear, and retrieve it.
String OTP = new String();
   
   try {

   driver.openNotifications();

   Thread.sleep(3000);

   List<AndroidElement> messageText =     driver.findElementsById("android:id/message_text");
   int Size = messageText.size();
   System.out.println("Size =" + Size);

   for(int i=0; i<=3; i++) {
      
      Thread.sleep(2000);
      if(OTP.length()==0) {
         OTP = OTPloop(Size, messageText);
      }else {
         System.out.println("OTP Found");
         break;
      }
   }  

   if(OTP.length()<6) {
      System.out.println("---- Failed to retrieve OTP ----");
      driver.pressKey(new KeyEvent(AndroidKey.BACK));
      return "";
   }else {
      OTP = extractOTP(OTP);
   }
   
   if(OTP.length()==0) {
      Assert.fail("OTP not received");
   }else {

      System.out.println("OTP is: " +  OTP);
   }
   
   driver.pressKey(new KeyEvent(AndroidKey.BACK));
   
   } catch (Exception e) {
      e.printStackTrace();
      return "";
   }
   return OTP;
}

private String OTPloop(int size, List<AndroidElement> element) {
   System.out.println("Inside OTP Loop method");
   for (int i = 0; i < size; i++) {
      System.out.println("Current position = " + i);
      if (element.get(i).getText().contains("OTP: ")) {
         return element.get(i).getText();
      }
   }
   return "";
}
private String extractOTP(String OTP) {
   
   Pattern p = Pattern.compile("\\d+");
   Matcher m = p.matcher(OTP);
   
   while(m.find()) {

      System.out.println(m.group().length());
      System.out.println(m.group());

      if(m.group().length()==6) {
         System.out.println("The OTP is: " + m.group());
         return m.group();
      }
   }return "";
}

Code Explanation

  • List messageText = driver.findElementsById(“android:id/message_text”) – This code will get the OTP message from the notification bar
  • OTP = OTPloop(Size, messageText) – It is a method, which will search for the given text “OTP: ” in that “messageText”. If found, it will retrieve the text from that element.
  • if(OTP.length()<6) - used for verifying the size of otp (change it according to your as varies from app app)
  • OTP = extractOTP(OTP); >> To extract the OTP using Regex

Note: Kindly change the locator according to your mobile element. We have taken the “messageText” locator for the following element.

how to test otp verification

Step 4: Enter the retrieved OTP in the OTP textbox.
try {
   AndroidElement otpBox = driver.findElement(By.id("in.amazon.mShop.android.shopping:id/otp_edit_text"));
   if (otpBox.isDisplayed()) {
      System.out.println("--------- Entering OTP ---------");
      if(otp != null) {
         otpBox.sendKeys(otp);
      }
   }

} catch (NoSuchElementException e) {
   System.out.println("OTP textbox not displayed");
}

Code Explanation

  • AndroidElement otpBox = driver.findElement(By.id(“in.amazon.mShop.android.shopping:id/otp_edit_text”)) – This line will get the OTP textbox element and store it in the “otpBox”
  • otpBox.sendKeys(otp); – Enter the retrieved OTP to the “otpBox”.

For the latest Android versions (From Android 14)

OTP will be automatically fetched in certain scenarios such as signup, login, or password recovery. However, for other cases like two-step verification, authenticator apps, or payment-related scenarios, you can follow the steps outlined above to automate OTP retrieval.

Conclusion

So those are the 4 simple steps that you can use to successfully automate OTP in Appium. Thank you for your time, we hope this blog has been informative and that you have enjoyed reading it. We also hope you are clear on how to automate OTP in Appium as it is a must-know technique that will come in handy for all automation testers. It has also been useful for us in helping us deliver the best Test Automation Services to our clients. We will constantly be updating such useful and technically sound blog articles on our website. So make sure you subscribe to our Newsletter so you don’t miss out on any of it. If you have any doubts about the above-discussed methods, or if you have any inputs that could make the process even more efficient, kindly head over to the comments section and let us know.

Frequently Asked Questions

  • How do you test OTP functionality?

    One can test the OTP functionality by checking how long it takes for the user to receive the OTP, if the OTP expires after the specified time, if the resend OTP option works, if the OTP is accepted, and if the transaction gets canceled after the defined number of invalid entries.

  • How to Automate OTP scenarios?

    OTP scenarios in Android can be automated using Appium either by retrieving the code from the notification bar or from the messages app used on the phone.

  • What does OTP stand for?

    OTP stands for One-time Password and as the name suggests, it is a single-use code received as an SMS or email to enable a secure verification process.

Comments(1)
  • 2 years ago

    In it something is. Now all became clear to me, I thank for the information.

Submit a Comment

Your email address will not be published. Required fields are marked *

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility