Automating OTP Retrieval Scenarios Using Appium: Necessary Steps and Code

Sam AtinksonSam Atinkson
5 min read

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.

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.

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.

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.

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.

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.

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.

Originally Published:- https://www.headspin.io/blog/step-by-step-guide-to-automate-otp-in-appium-along-with-necessary-code

0
Subscribe to my newsletter

Read articles from Sam Atinkson directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sam Atinkson
Sam Atinkson

Sam Atkinson is a results-driven SEO Executive with 3 Years of experience in optimizing digital visibility and driving organic growth. Skilled in developing and executing strategic SEO initiatives, Sam excels in keyword research, technical audits, and competitor analysis to elevate online presence and improve search engine rankings. With a keen eye for detail and a passion for delivering measurable results, Sam collaborates cross-functionally to align SEO efforts with business objectives and enhance website performance. Committed to staying ahead of industry trends.