Join the webinar on 'Open source GenAI tools for Test Automation' on May 28th or May 30th.
close
How To Automate OTP in Appium – Process & Code

Automating OTP Retrieval Scenarios Using Appium: Necessary Steps and Code

June 27, 2023
 by 
Rohan SinghRohan Singh
Rohan Singh

Appium, recognized as one of the best mobile app automation frameworks available, offers a fundamental technique that every automation tester should be proficient in: automating OTP in Appium. While some may question the need for automating OTP when developers can easily make it static for testing purposes, it's important to understand the limitations of this approach. This solution works only in the STAGE or DEV environment and is impractical in a production environment where repetitive execution of the same static OTP automation script is not feasible.

This blog explores how to automate OTP in Appium using four simple steps. By seamlessly incorporating the retrieval and input of OTPs into our Appium scripts, we can improve testing efficiency and ensure the smooth operation and reliability of mobile applications.

Read: Different types of test automation frameworks

How to Retrieve OTP Using Appium

When automating the OTP scenario using Appium on an Android device, there are two approaches to consider:

  • Utilizing the notification bar: In this method, we can extract the OTP by accessing the notification bar of the device.
  • Opening the 'messages' app: Alternatively, we can navigate to the 'messages' app and retrieve the OTP from there.

In the realm of Appium OTP automation, this blog will primarily delve into retrieving the OTP from the notification bar. This approach offers a simpler and more streamlined method, allowing testers to maintain focus on the targeted app during testing. Let's begin by exploring the essential prerequisites required to accomplish this task effectively.

Also read: Installing Appium 2.0 and the Driver and Plugins CLI

Before we begin, ensure you have the following prerequisites:

  1. Appium and its dependencies are installed on your machine.
  2. A mobile device or emulator connected and recognized by Appium.
  3. An app installed on the device that requires OTP verification.

Steps and Corresponding Code Involved in Automating OTP Retrieval Using Appium

This process involves breaking down the Java code into its essential components and explaining them thoroughly. By following along with the explanations and taking note of specific details mentioned, you'll gain a clear understanding of how to automate OTP in Appium. Now, let's proceed to explore the code implementation.

Step 1: Opening the Notification Panel and Clearing Previous Notifications

To initiate the automation of OTP retrieval, we first need to open the notification panel and clear any existing notifications. Let's dive into the code snippet that demonstrates this using Appium:


import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidKeyCode;
import org.openqa.selenium.remote.DesiredCapabilities;
 
// Set desired capabilities
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("deviceName", "YourDeviceName");
caps.setCapability("platformName", "Android");
 
// Create AndroidDriver instance
AndroidDriver driver = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"), caps);
 
// Open notification panel
driver.openNotifications();
 
// Clear previous notifications
driver.findElementByXPath("//android.widget.TextView[@text='Clear all']").click();

In the above code, we set the desired capabilities for the Android device, create an AndroidDriver instance, and then open the notification panel using driver.openNotifications(). We then locate and click the "Clear all" button to remove any previous notifications.

Test your apps on real devices and get accurate results. Know more

Step 2: Entering the Mobile Number

Next, we need to write code to automate the step where the user is asked to enter their mobile number. You can achieve this by locating the mobile number input field and entering the desired number. Here's an example code snippet:


// Find the mobile number input field
driver.findElementById("com.example.app:id/mobileNumberField").sendKeys("1234567890");
Ensure that you replace "com.example.app:id/mobileNumberField" with the actual identifier of the mobile number input field in your app.
Check out: Active Testing SMS with HeadSpin

Step 3: Retrieving the OTP from the Notification Panel

After entering the mobile number, we must wait for the OTP to appear in the notification panel, retrieve it, and store it for further use. The following code snippet demonstrates this process:


// Wait for the OTP notification
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//android.widget.TextView[contains(@text, 'OTP')]")));
 
// Retrieve the OTP text
String otpText = driver.findElement(By.xpath("//android.widget.TextView[contains(@text, 'OTP')]")).getText();
String otp = otpText.replaceAll("[^0-9]", ""); // Extract only the numeric OTP value
The above code waits for the OTP notification to appear using WebDriverWait. We use an XPath expression to locate the OTP notification text, extract the text content, and then filter out the numeric OTP value using replaceAll("[^0-9]", ""). Modify the XPath expression ("//android.widget.TextView[contains(@text, 'OTP')]") to match your app's notification content.

Also check: Using Appium for Automated Testing of Roku TV Apps

Step 4: Entering the Retrieved OTP

Finally, we can automate the step of entering the retrieved OTP into the OTP textbox within the application. Here's an example code snippet:


// Find the OTP input field
driver.findElementById("com.example.app:id/otpField").sendKeys(otp);
Replace "com.example.app:id/otpField" with the actual identifier of the OTP input field in your app.

How HeadSpin Can Enhance Your Appium-driven Test Automation Processes

HeadSpin offers a range of advanced capabilities that enhance the benefits of Appium for mobile app testing. With real-time, global, and multi-network testing, as well as comprehensive performance monitoring and insightful analytics, developers can ensure their apps deliver a seamless user experience across various devices.

Here are some key advantages of integrating HeadSpin with your Appium testing:

  • Seamless Integration: Integrate your existing Appium tests effortlessly with the HeadSpin Platform and execute them on any device.
  • Streamlined Development: Debug and develop Appium scripts directly within the intuitive HeadSpin UI, making the testing process more efficient.
  • Load Balancing: Leverage the HeadSpin Appium load balancer to distribute tests effectively, ensuring optimal resource utilization and faster execution.
  • Performance Insights: Capture detailed performance data during testing, enabling you to gain actionable insights and optimize your app's performance.
  • Parallel Testing: Execute tests in parallel using HeadSpin, reducing time consumption and accelerating the overall testing process.

By leveraging the power of HeadSpin in conjunction with Appium, developers can elevate their testing capabilities, validate app performance, and deliver an exceptional user experience on a global scale.

Learn more: Appium vs. Espresso — which one to use for automating Android app testing

Wrapping Up

Automating OTP verification in Appium is a fundamental technique for efficient and reliable mobile app testing. By following these four steps outlined in this blog, you can seamlessly integrate OTP automation into your Appium test scripts. From accessing the notification panel and clearing previous notifications to accurately entering the OTP, these steps streamline the testing process. Mastering this technique of automating OTP with Appium is essential for any automation tester, and it proves invaluable in testing endeavors. 

Enhance the quality of your mobile app testing by seamlessly automating OTP verification with the HeadSpin Platform integrated with Appium. This powerful integration empowers you to achieve reliable results and deliver perfect digital experiences with ease.

Book a trial

FAQs

Q1. What are the challenges of automating OTP testing?

Ans: Some challenges of automating OTP testing include:

  • OTP expiration: The OTP may expire before it can be entered into the app. This is a challenge due to the difficulty in determining the time it would take the user to retrieve the OTP from the notification and enter it into the app.
  • Incorrect entry: The OTP may be entered incorrectly. Ensuring that the user enters the OTP correctly can be challenging.
  • Network issues: The app may not be able to connect to the network to obtain the OTP, which can prevent the user from logging into the app.
  • Notification display issues: The app may not be able to display the OTP notification, which can prevent the user from retrieving the OTP from the notification.

Q2. Can OTP automation in Appium be used for both Android and iOS applications?

Ans: Yes, OTP automation in Appium can be used for both Android and iOS applications. Appium is a cross-platform mobile automation framework that supports testing on Android as well as iOS devices. The techniques and code for automating OTP entry are similar for both platforms. However, there might be slight variations in accessing SMS or email sources to extract OTPs, as the implementation may differ between Android and iOS.

Q3. Are there any security concerns with automating OTP in Appium?

Ans: Yes, there are security concerns with automating OTP entry in Appium. OTPs are sensitive information and mishandling them can lead to security vulnerabilities. To mitigate such risks, it is advised to follow these best practices:

  • Use test accounts or test environments.
  • Encrypt or obfuscate OTP values.
  • Securely handle OTP sources.
  • Implement test-specific OTP generation.
  • Limit access to OTP-related code or scripts.

Automating OTP Retrieval Scenarios Using Appium: Necessary Steps and Code

4 Parts

Close

Perfect Digital Experiences with Data Science Capabilities

Utilize HeadSpin's advanced capabilities to proactively improve performance and launch apps with confidence
popup image