SlideShare a Scribd company logo
Appium Automation with Kotlin
Appium Automation with Kotlin
© RapidValue Solutions 2
Appium Automation with Kotlin
Pre-requisites:
Following are the pre-requisites to start Appium with Kotlin:
 Install Java SDK 8 and above.
 Install Eclipse or IntelliJ IDEA IDEs.
 Install the Kotlin plugin in IDEs. Here I am using Eclipse as IDE and Kotlin plugin for Eclipse
downloaded from https://marketplace.eclipse.org/content/kotlin-plugin-eclipse
 The latest version of following maven dependencies:
o testing
o selenium-java
o selenium-server
o java-client
o kotlin-test
o kotlin-stdlib-jdk8
o extentreports
Step-by-step Procedure
Step 1: Create a maven project and add the above dependencies in pom.xml of the project.
Step 2: Create a Kotlin class to keep the logic to initiate the driver and start the Appium server. Let’s say the
class name is AutomationBase. We are defining this class as an abstract class. So, it is easy to extend by
other classes. We have implemented startApplication, startAppiumServer, getPort, getNodePath,
getJSPath, getDriverInstance and setDriverInstance methods in the AutomationBase class. Below are
the sample code snippets:
fun startApplication() {
try {
var service: AppiumDriverLocalService = startAppiumServer()
var capabilities = DesiredCapabilities()
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, “One Plus”)
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, “Android”)
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, “10”)
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME,
AutomationName.ANDROID_UIAUTOMATOR2)
capabilities.setCapability(AndroidMobileCapabilityType.AUTO_GRANT_PERMISSIONS, true)
capabilities.setCapability(“newCommandTimeout”, 180)
capabilities.setCapability(“udid”, “e6916f40”)
capabilities.setCapability(MobileCapabilityType.APP, “YOUR_APP_PATH”)
capabilities.setCapability(MobileCapabilityType.NO_RESET, true)
if(!service.toString().isEmpty()){
driver = AndroidDriver(service.getUrl(), capabilities)
}
} catch (e: Exception) {
Appium Automation with Kotlin
© RapidValue Solutions 3
e.printStackTrace()
}
}
private fun startAppiumServer(): AppiumDriverLocalService {
var IP_ADDRESS: String = “127.0.0.1”
var bootStrapPort: String
var chromePort: String
var port: Int
if (!File(System.getProperty(“user.dir”) + “LogsAppium_logs”).exists()) {
(File(System.getProperty(“user.dir”) + “Logs”)).mkdir()
(File(System.getProperty(“user.dir”) + “LogsAppium_logs”)).mkdir()
}
port = getPort()
bootStrapPort = Integer.toString(getPort())
chromePort = Integer.toString(getPort())
var service = AppiumDriverLocalService.buildService(
AppiumServiceBuilder().withAppiumJS(File(getJSPath()))
.usingDriverExecutable(File(getNodePath())).withIPAddress(IP_ADDRESS).usingPort(port)
.withArgument(AndroidServerFlag.BOOTSTRAP_PORT_NUMBER, bootStrapPort)
.withArgument(AndroidServerFlag.CHROME_DRIVER_PORT, chromePort)
.withLogFile(File(System.getProperty(“user.dir”) + “LogsAppium_logsappiumLogs.txt”)))
service.start()
if (service.isRunning()) {
System.out.println(“Server is running…..” + service)
} else {
System.out.println(“Server startup failed…..”)
System.exit(0)
}
return service
}
private fun getPort(): Int {
var port: Int = 0
try {
var socket = ServerSocket(0)
socket.setReuseAddress(true)
port = socket.getLocalPort()
socket.close()
} catch (e: Exception) {
e.printStackTrace()
}
return port
}
private fun getNodePath(): String {
var nodePath: String
var p: Process
var reader: BufferedReader
var command: String
Appium Automation with Kotlin
© RapidValue Solutions 4
var operatingSystem: String = System.getProperty(“os.name”)
if (operatingSystem.contains(“Win”)) {
command = “where” + ” ” + “node”
} else {
command = “which ” + “node”
}
p = Runtime.getRuntime().exec(command)
reader = BufferedReader(InputStreamReader(p.getInputStream()))
nodePath = reader.readLine()
p.waitFor()
p.destroy()
return nodePath
}
fun getJSPath(): String {
var jsPaths: String
lateinit var actualJSPath: String
var command: String
var operatingSystem: String = System.getProperty(“os.name”)
if (operatingSystem.contains(“Win”)) {
command = “where” + ” ” + “appium”
var p: Process = Runtime.getRuntime().exec(command)
var stdInput: BufferedReader = BufferedReader(InputStreamReader(p.getInputStream()))
jsPaths = stdInput.readLine()
actualJSPath = jsPaths.replace(“appium”, “node_modulesappiumbuildlibmain.js”)
p.waitFor()
p.destroy()
} else {
actualJSPath = “//usr//local//lib//node_modules//appium//build//lib//main.js”
}
return actualJSPath
}
fun getDriverInstance(): WebDriver {
return this.driver
}
fun setDriverInstance(driver: WebDriver) {
this.driver = driver
}
startApplication method helps to instantiate driver sessions based on the specified capabilities.
startAppiumServer method helps to start the Appium server and also, create and write server logs to a text
file. getPort method helps to create the dynamic network port that supports the startAppiumServer
method. getNodePath method helps to get the node path and it supports the startAppiumServer method.
getJSPath method helps to get the Appium main.js path and it supports the startAppiumServer method.
Step 3: Create a TestRunner class and it extends AutomationBase class. This class holds TestNG
annotations @Listeners, @BeforeClass, and @AfterSuite. Below are the complete code snippets:
Appium Automation with Kotlin
© RapidValue Solutions 5
@Listeners(AutomationReport::class)
open class TestRunner : AutomationBase() {
@BeforeClass
fun setUp() {
startApplication()
}
@AfterSuite
fun tearDown() {
Thread.sleep(3000)
driver.quit()
}
}
Step 4: Create a sample test class to keep the test cases. Let’s call it SampleTests and it
extends TestRunner class. Following are the sample code snippets:
class SampleTests : TestRunner() {
@Test
fun TC001_testEnterPincode() {
SampleTestsHelper.enterPinCode(driver, “682030”)
}
@Test
fun TC002_testSearchFail() {
Assert.fail()
}
}
Step 5: Create a Kotlin class which should act as a helper class of test class. Let’s call it
SampleTestsHelper and define this SampleTestsHelper as object. So, Kotlin will create an instance
automatically when we invoke the methods of SampleTestsHelper. No need to create a separate instance to
invoke the methods of the helper class. Below are the complete code snippets:
object SampleTestsHelper {
/**
* This method used to enter pin code
*
* @author sanojs
* @since 01-09-2020
*/
fun enterPinCode(driver: WebDriver, valueToSearch: String) {
Appium Automation with Kotlin
© RapidValue Solutions 6
try {
driver.findElement(By.id(“in.dmart:id/et_activity_pincode_pincode”)).sendKeys(pincod)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
Step 6: Create a Kotlin class to keep the logic to generate an Automation test execution report in HTML
format. Let’s say the class name as AutomationReport. Here, we are using extentreports library to
generate an HTML report. Also, we are using ITestListener interface to control the executions and results.
Below are the complete code snippets of the AutomationReport class,
class AutomationReport : ITestListener {
public lateinit var sparkReporter: ExtentSparkReporter
public lateinit var extentReport: ExtentReports
public lateinit var extentTest: ExtentTest
/**
* This override method used to create HTML template for the test report
*
* @author sanojs
* @since 01-09-2020
*/
override fun onStart(testContext: ITestContext) {
try {
sparkReporter = ExtentSparkReporter(System.getProperty(“user.dir”) + “/AutomationReport/”)
sparkReporter.config().setDocumentTitle(“Appium Kotlin Automation”)
sparkReporter.config().setReportName(“Automation Execution Report”)
sparkReporter.config().setTheme(com.aventstack.extentreports.reporter.configuration.Theme.DARK)
extentReport = ExtentReports()
extentReport.attachReporter(sparkReporter)
extentReport.setSystemInfo(“Application Name”, “Kotlin Appium Demo”)
extentReport.setSystemInfo(“Platform”, System.getProperty(“os.name”))
extentReport.setSystemInfo(“Environment”, “QA”)
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* This override method used to collect current test case name add to the report
*
* @author sanojs
* @since 01-09-2020
*/
override fun onTestStart(result: ITestResult) {
var testName: String = result.getMethod().getMethodName()
extentTest = extentReport.createTest(testName)
Appium Automation with Kotlin
© RapidValue Solutions 7
}
/**
* This override method used to add pass status to the report
*
* @author sanojs
* @since 01-09-2020
*/
override fun onTestSuccess(result: ITestResult) {
var testName: String = result.getMethod().getMethodName()
try {
extentTest.log(
Status.PASS,
MarkupHelper.createLabel(testName + ” Test Case PASSED”, ExtentColor.GREEN)
)
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* This override method used to add fail status to the report
*
* @author sanojs
* @since 01-09-2020
*/
override fun onTestFailure(result: ITestResult) {
var driver: WebDriver
var currentClass = result.getInstance()
var testName: String = result.getMethod().getMethodName()
try {
driver = (currentClass as AutomationBase).getDriverInstance()
var screenshotPath = Utilities().screenshotCapture(driver, result.getName())
extentTest.log(
Status.FAIL,
MarkupHelper.createLabel(testName + ” Test Case FAILED”, ExtentColor.RED)
)
extentTest.log(
Status.FAIL,
MarkupHelper.createLabel(“Reason for Failure: ” + result.getThrowable().toString(),
ExtentColor.RED)
)
extentTest.addScreenCaptureFromPath(screenshotPath)
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* This override method used to add skip status to the report
*
* @author sanojs
* @since 01-09-2020
*/
Appium Automation with Kotlin
© RapidValue Solutions 8
override fun onTestSkipped(result: ITestResult) {
var testName: String = result.getMethod().getMethodName()
try {
extentTest.log(
Status.SKIP,
MarkupHelper.createLabel(testName + ” Test Case SKIPPED”, ExtentColor.ORANGE)
)
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* This override method used to store HTML report to the specified path and flush extent report
instance
*
* @author sanojs
* @since 01-09-2020
*/
override fun onFinish(testContext: ITestContext) {
try {
extentReport.flush()
val dateFormat = SimpleDateFormat(“dd-MMM-yyyy_HH-mm-ss”)
val date = Date()
val filePathdate: String = dateFormat.format(date).toString()
var actualReportPath: String = System.getProperty(“user.dir”) + “/AutomationReport/” +
“index.html”
File(actualReportPath).renameTo(
File(
System.getProperty(“user.dir”) + “/AutomationReport/”
+ “Automation_Report_” + filePathdate + “.html”
)
)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
Step 7: Create another class called Utilities to keep common utility functions required for automation. Here,
we just added one utility to capture the screenshot. Below is the code snippet to capture the screenshot,
fun screenshotCapture(driver: WebDriver, fileName: String): String {
var destination: String = “”
try {
var scrFile = (driver as TakesScreenshot).getScreenshotAs(OutputType.FILE)
var dateFormat = SimpleDateFormat(“yyyyMMddHHmmss”)
var cal = Calendar.getInstance()
var path = File(“Failure_Screenshots”).getAbsolutePath()
destination = path + “/” + fileName + dateFormat.format(cal.getTime()) + “.png”
scrFile.copyTo(File(destination))
Appium Automation with Kotlin
© RapidValue Solutions 9
} catch (e: Exception) {
e.printStackTrace()
}
return destination
}
Step 8: Add a testng.xml file into the project structure and map your test classes into the testng.xml to run
the test cases. Once the execution is complete, the HTML report will get generated inside
the AutomationReport folder in the project structure.
Below is the overall project structure of Appium with Kotlin:
NOTE:
 Kotlin Runtime Library will automatically get added to the build path of the project when you create
a Kotlin class under any package.
 Kotlin class extension is .kt
 The semicolon is not mandatory to end the statements in the class.
 While inheriting a class from a parent class you have to declare the parent class as open, using
an open keyword or you can declare the parent class as abstract using abstract. You can’t inherit a
singleton class. So avoid extending the class which is declared as object in Kotlin.
 If you declare a class with an object keyword then no need to create an instance. Kotlin will create
an instance to access the methods or variables of that class.
Appium Automation with Kotlin
© RapidValue Solutions 10
Conclusion
Kotlin is a general-purpose, open-source, statically typed programming language that combines object-
oriented and functional programming features. So, Kotlin is a strong and powerful language that helps the
automation engineers to write their automation script for Appium. This article aims to help the Appium
automation engineers to upskill and write their scripting in a different language such as Kotlin.
By,
Sanoj S, Test Architect, RapidValue
Appium Automation with Kotlin
© RapidValue Solutions 11
About RapidValue
RapidValue is a global leader in digital product engineering solutions including mobility, omni-channel, IoT, AI, RPA
and cloud to enterprises worldwide. RapidValue offers its digital services to the world’s top brands, Fortune 1000
companies and innovative emerging start-ups. With offices in the United States, the United Kingdom, Germany and
India and operations spread across the Middle-East, Europe and Canada, RapidValue delivers enterprise services
and solutions across various industry verticals.
Disclaimer:
This document contains information that is confidential and proprietary to RapidValue Solutions Inc. No part of it may be used, circulated, quoted,
or reproduced for distribution outside RapidValue. If you are not the intended recipient of this report, you are hereby notified that the use,
circulation, quoting, or reproducing of this report is strictly prohibited and may be unlawful.
www.rapidvaluesolutions.com/blogwww.rapidvaluesolutions.com
+1 877.643.1850 contactus@rapidvaluesolutions.com

More Related Content

What's hot (20)

PPTX
Git and git workflow best practice
Majid Hosseini
 
PDF
OpenID Connect のビジネスチャンス
OpenID Foundation Japan
 
PDF
A Guide to Adopting Kubernetes
NGINX, Inc.
 
PPTX
OpenTelemetry 101 FTW
NGINX, Inc.
 
PPTX
Identity and access management
Piyush Jain
 
PPTX
NGINXをBFF (Backend for Frontend)として利用した話
Hitachi, Ltd. OSS Solution Center.
 
PDF
【NGINXセミナー】API ゲートウェイとしてのNGINX Plus活用方法
NGINX, Inc.
 
PPTX
法人認証基盤GビズIDと今後の法人KYC - OpenID BizDay #14
OpenID Foundation Japan
 
ODP
Logging presentation
Jatan Malde
 
PPTX
Bitglass Webinar - Top 6 CASB Use Cases
Bitglass
 
PDF
採用 OPNsense 開源防火牆打造橫跨 IT/OT 的堅強防護 @台灣國際認證資安專家協會 @台中高鐵站集思會議中心史蒂文生廳
Jason Cheng
 
PDF
Accelerate Microservices Deployments with Automation
NGINX, Inc.
 
PDF
LINE Login総復習
Naohiro Fujie
 
PDF
Unit 1: Apply the Twelve-Factor App to Microservices Architectures
NGINX, Inc.
 
PPTX
Database Migrations with Gradle and Liquibase
Dan Stine
 
PDF
NGINX基本セミナー(セキュリティ編)~NGINXでセキュアなプラットフォームを実現する方法!
NGINX, Inc.
 
PPTX
IT資産の可視化とIT構成の最適化
UNIRITA Incorporated
 
PPTX
OpenTelemetry: The future (present) of Observability
Gustavo Corrêa Alves
 
PPTX
Git presentation
Sai Kumar Satapathy
 
PDF
Distributed Tracing
distributedtracing
 
Git and git workflow best practice
Majid Hosseini
 
OpenID Connect のビジネスチャンス
OpenID Foundation Japan
 
A Guide to Adopting Kubernetes
NGINX, Inc.
 
OpenTelemetry 101 FTW
NGINX, Inc.
 
Identity and access management
Piyush Jain
 
NGINXをBFF (Backend for Frontend)として利用した話
Hitachi, Ltd. OSS Solution Center.
 
【NGINXセミナー】API ゲートウェイとしてのNGINX Plus活用方法
NGINX, Inc.
 
法人認証基盤GビズIDと今後の法人KYC - OpenID BizDay #14
OpenID Foundation Japan
 
Logging presentation
Jatan Malde
 
Bitglass Webinar - Top 6 CASB Use Cases
Bitglass
 
採用 OPNsense 開源防火牆打造橫跨 IT/OT 的堅強防護 @台灣國際認證資安專家協會 @台中高鐵站集思會議中心史蒂文生廳
Jason Cheng
 
Accelerate Microservices Deployments with Automation
NGINX, Inc.
 
LINE Login総復習
Naohiro Fujie
 
Unit 1: Apply the Twelve-Factor App to Microservices Architectures
NGINX, Inc.
 
Database Migrations with Gradle and Liquibase
Dan Stine
 
NGINX基本セミナー(セキュリティ編)~NGINXでセキュアなプラットフォームを実現する方法!
NGINX, Inc.
 
IT資産の可視化とIT構成の最適化
UNIRITA Incorporated
 
OpenTelemetry: The future (present) of Observability
Gustavo Corrêa Alves
 
Git presentation
Sai Kumar Satapathy
 
Distributed Tracing
distributedtracing
 

Similar to Appium Automation with Kotlin (20)

PDF
Getting started with appium
Pratik Patel
 
PDF
Appium understanding document
Akshay Pillay
 
PPT
Appium
Keshav Kashyap
 
PDF
20150319 testotipsio
Kazuaki Matsuo
 
PPTX
Appium overview
Abhishek Yadav
 
PPT
Android & iOS Automation Using Appium
Mindfire Solutions
 
DOCX
AppiumSetupConfigurationonWindows
Lalit Ghule
 
PDF
Android UI Testing with Appium
Luke Maung
 
PDF
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
kalichargn70th171
 
PPT
Appium
Deepshikha Singh
 
PDF
A Step-by-Step Guide to Test Automation with Appium.pdf
flufftailshop
 
PPTX
Mobile Automation with Appium
Manoj Kumar Kumar
 
PDF
Appium workshop technopark trivandrum
Syam Sasi
 
PDF
Guide to Generate Extent Report in Kotlin
RapidValue
 
PPTX
Appium Mobile Testing: Nakov at BurgasConf - July 2021
Svetlin Nakov
 
PPTX
Mobile automation using Appium
Saroj Singh
 
PPTX
Appium testing api
b4usolution .
 
PPTX
How to Leverage Appium in Your Mobile App Testing
Bitbar
 
PDF
How to kill test flake in appium
Gaurav Singh
 
PPTX
Android CI and Appium
Oren Ashkenazy
 
Getting started with appium
Pratik Patel
 
Appium understanding document
Akshay Pillay
 
20150319 testotipsio
Kazuaki Matsuo
 
Appium overview
Abhishek Yadav
 
Android & iOS Automation Using Appium
Mindfire Solutions
 
AppiumSetupConfigurationonWindows
Lalit Ghule
 
Android UI Testing with Appium
Luke Maung
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
kalichargn70th171
 
A Step-by-Step Guide to Test Automation with Appium.pdf
flufftailshop
 
Mobile Automation with Appium
Manoj Kumar Kumar
 
Appium workshop technopark trivandrum
Syam Sasi
 
Guide to Generate Extent Report in Kotlin
RapidValue
 
Appium Mobile Testing: Nakov at BurgasConf - July 2021
Svetlin Nakov
 
Mobile automation using Appium
Saroj Singh
 
Appium testing api
b4usolution .
 
How to Leverage Appium in Your Mobile App Testing
Bitbar
 
How to kill test flake in appium
Gaurav Singh
 
Android CI and Appium
Oren Ashkenazy
 
Ad

More from RapidValue (20)

PDF
How to Build a Micro-Application using Single-Spa
RapidValue
 
PDF
Play with Jenkins Pipeline
RapidValue
 
PDF
Accessibility Testing using Axe
RapidValue
 
PDF
Automation in Digital Cloud Labs
RapidValue
 
PDF
Microservices Architecture - Top Trends & Key Business Benefits
RapidValue
 
PDF
Uploading Data Using Oracle Web ADI
RapidValue
 
PDF
Build UI of the Future with React 360
RapidValue
 
PDF
Python Google Cloud Function with CORS
RapidValue
 
PDF
Real-time Automation Result in Slack Channel
RapidValue
 
PDF
Automation Testing with KATALON Cucumber BDD
RapidValue
 
PDF
How to Implement Micro Frontend Architecture using Angular Framework
RapidValue
 
PDF
Video Recording of Selenium Automation Flows
RapidValue
 
PDF
JMeter JMX Script Creation via BlazeMeter
RapidValue
 
PDF
Migration to Extent Report 4
RapidValue
 
PDF
The Definitive Guide to Implementing Shift Left Testing in QA
RapidValue
 
PDF
Data Seeding via Parameterized API Requests
RapidValue
 
PDF
Test Case Creation in Katalon Studio
RapidValue
 
PDF
How to Perform Memory Leak Test Using Valgrind
RapidValue
 
PDF
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValue
RapidValue
 
PDF
A Technology Backgrounder to Serverless Architecture - A Whitepaper by RapidV...
RapidValue
 
How to Build a Micro-Application using Single-Spa
RapidValue
 
Play with Jenkins Pipeline
RapidValue
 
Accessibility Testing using Axe
RapidValue
 
Automation in Digital Cloud Labs
RapidValue
 
Microservices Architecture - Top Trends & Key Business Benefits
RapidValue
 
Uploading Data Using Oracle Web ADI
RapidValue
 
Build UI of the Future with React 360
RapidValue
 
Python Google Cloud Function with CORS
RapidValue
 
Real-time Automation Result in Slack Channel
RapidValue
 
Automation Testing with KATALON Cucumber BDD
RapidValue
 
How to Implement Micro Frontend Architecture using Angular Framework
RapidValue
 
Video Recording of Selenium Automation Flows
RapidValue
 
JMeter JMX Script Creation via BlazeMeter
RapidValue
 
Migration to Extent Report 4
RapidValue
 
The Definitive Guide to Implementing Shift Left Testing in QA
RapidValue
 
Data Seeding via Parameterized API Requests
RapidValue
 
Test Case Creation in Katalon Studio
RapidValue
 
How to Perform Memory Leak Test Using Valgrind
RapidValue
 
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValue
RapidValue
 
A Technology Backgrounder to Serverless Architecture - A Whitepaper by RapidV...
RapidValue
 
Ad

Recently uploaded (20)

PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 

Appium Automation with Kotlin

  • 2. Appium Automation with Kotlin © RapidValue Solutions 2 Appium Automation with Kotlin Pre-requisites: Following are the pre-requisites to start Appium with Kotlin:  Install Java SDK 8 and above.  Install Eclipse or IntelliJ IDEA IDEs.  Install the Kotlin plugin in IDEs. Here I am using Eclipse as IDE and Kotlin plugin for Eclipse downloaded from https://marketplace.eclipse.org/content/kotlin-plugin-eclipse  The latest version of following maven dependencies: o testing o selenium-java o selenium-server o java-client o kotlin-test o kotlin-stdlib-jdk8 o extentreports Step-by-step Procedure Step 1: Create a maven project and add the above dependencies in pom.xml of the project. Step 2: Create a Kotlin class to keep the logic to initiate the driver and start the Appium server. Let’s say the class name is AutomationBase. We are defining this class as an abstract class. So, it is easy to extend by other classes. We have implemented startApplication, startAppiumServer, getPort, getNodePath, getJSPath, getDriverInstance and setDriverInstance methods in the AutomationBase class. Below are the sample code snippets: fun startApplication() { try { var service: AppiumDriverLocalService = startAppiumServer() var capabilities = DesiredCapabilities() capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, “One Plus”) capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, “Android”) capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, “10”) capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2) capabilities.setCapability(AndroidMobileCapabilityType.AUTO_GRANT_PERMISSIONS, true) capabilities.setCapability(“newCommandTimeout”, 180) capabilities.setCapability(“udid”, “e6916f40”) capabilities.setCapability(MobileCapabilityType.APP, “YOUR_APP_PATH”) capabilities.setCapability(MobileCapabilityType.NO_RESET, true) if(!service.toString().isEmpty()){ driver = AndroidDriver(service.getUrl(), capabilities) } } catch (e: Exception) {
  • 3. Appium Automation with Kotlin © RapidValue Solutions 3 e.printStackTrace() } } private fun startAppiumServer(): AppiumDriverLocalService { var IP_ADDRESS: String = “127.0.0.1” var bootStrapPort: String var chromePort: String var port: Int if (!File(System.getProperty(“user.dir”) + “LogsAppium_logs”).exists()) { (File(System.getProperty(“user.dir”) + “Logs”)).mkdir() (File(System.getProperty(“user.dir”) + “LogsAppium_logs”)).mkdir() } port = getPort() bootStrapPort = Integer.toString(getPort()) chromePort = Integer.toString(getPort()) var service = AppiumDriverLocalService.buildService( AppiumServiceBuilder().withAppiumJS(File(getJSPath())) .usingDriverExecutable(File(getNodePath())).withIPAddress(IP_ADDRESS).usingPort(port) .withArgument(AndroidServerFlag.BOOTSTRAP_PORT_NUMBER, bootStrapPort) .withArgument(AndroidServerFlag.CHROME_DRIVER_PORT, chromePort) .withLogFile(File(System.getProperty(“user.dir”) + “LogsAppium_logsappiumLogs.txt”))) service.start() if (service.isRunning()) { System.out.println(“Server is running…..” + service) } else { System.out.println(“Server startup failed…..”) System.exit(0) } return service } private fun getPort(): Int { var port: Int = 0 try { var socket = ServerSocket(0) socket.setReuseAddress(true) port = socket.getLocalPort() socket.close() } catch (e: Exception) { e.printStackTrace() } return port } private fun getNodePath(): String { var nodePath: String var p: Process var reader: BufferedReader var command: String
  • 4. Appium Automation with Kotlin © RapidValue Solutions 4 var operatingSystem: String = System.getProperty(“os.name”) if (operatingSystem.contains(“Win”)) { command = “where” + ” ” + “node” } else { command = “which ” + “node” } p = Runtime.getRuntime().exec(command) reader = BufferedReader(InputStreamReader(p.getInputStream())) nodePath = reader.readLine() p.waitFor() p.destroy() return nodePath } fun getJSPath(): String { var jsPaths: String lateinit var actualJSPath: String var command: String var operatingSystem: String = System.getProperty(“os.name”) if (operatingSystem.contains(“Win”)) { command = “where” + ” ” + “appium” var p: Process = Runtime.getRuntime().exec(command) var stdInput: BufferedReader = BufferedReader(InputStreamReader(p.getInputStream())) jsPaths = stdInput.readLine() actualJSPath = jsPaths.replace(“appium”, “node_modulesappiumbuildlibmain.js”) p.waitFor() p.destroy() } else { actualJSPath = “//usr//local//lib//node_modules//appium//build//lib//main.js” } return actualJSPath } fun getDriverInstance(): WebDriver { return this.driver } fun setDriverInstance(driver: WebDriver) { this.driver = driver } startApplication method helps to instantiate driver sessions based on the specified capabilities. startAppiumServer method helps to start the Appium server and also, create and write server logs to a text file. getPort method helps to create the dynamic network port that supports the startAppiumServer method. getNodePath method helps to get the node path and it supports the startAppiumServer method. getJSPath method helps to get the Appium main.js path and it supports the startAppiumServer method. Step 3: Create a TestRunner class and it extends AutomationBase class. This class holds TestNG annotations @Listeners, @BeforeClass, and @AfterSuite. Below are the complete code snippets:
  • 5. Appium Automation with Kotlin © RapidValue Solutions 5 @Listeners(AutomationReport::class) open class TestRunner : AutomationBase() { @BeforeClass fun setUp() { startApplication() } @AfterSuite fun tearDown() { Thread.sleep(3000) driver.quit() } } Step 4: Create a sample test class to keep the test cases. Let’s call it SampleTests and it extends TestRunner class. Following are the sample code snippets: class SampleTests : TestRunner() { @Test fun TC001_testEnterPincode() { SampleTestsHelper.enterPinCode(driver, “682030”) } @Test fun TC002_testSearchFail() { Assert.fail() } } Step 5: Create a Kotlin class which should act as a helper class of test class. Let’s call it SampleTestsHelper and define this SampleTestsHelper as object. So, Kotlin will create an instance automatically when we invoke the methods of SampleTestsHelper. No need to create a separate instance to invoke the methods of the helper class. Below are the complete code snippets: object SampleTestsHelper { /** * This method used to enter pin code * * @author sanojs * @since 01-09-2020 */ fun enterPinCode(driver: WebDriver, valueToSearch: String) {
  • 6. Appium Automation with Kotlin © RapidValue Solutions 6 try { driver.findElement(By.id(“in.dmart:id/et_activity_pincode_pincode”)).sendKeys(pincod) } catch (e: Exception) { e.printStackTrace() } } } Step 6: Create a Kotlin class to keep the logic to generate an Automation test execution report in HTML format. Let’s say the class name as AutomationReport. Here, we are using extentreports library to generate an HTML report. Also, we are using ITestListener interface to control the executions and results. Below are the complete code snippets of the AutomationReport class, class AutomationReport : ITestListener { public lateinit var sparkReporter: ExtentSparkReporter public lateinit var extentReport: ExtentReports public lateinit var extentTest: ExtentTest /** * This override method used to create HTML template for the test report * * @author sanojs * @since 01-09-2020 */ override fun onStart(testContext: ITestContext) { try { sparkReporter = ExtentSparkReporter(System.getProperty(“user.dir”) + “/AutomationReport/”) sparkReporter.config().setDocumentTitle(“Appium Kotlin Automation”) sparkReporter.config().setReportName(“Automation Execution Report”) sparkReporter.config().setTheme(com.aventstack.extentreports.reporter.configuration.Theme.DARK) extentReport = ExtentReports() extentReport.attachReporter(sparkReporter) extentReport.setSystemInfo(“Application Name”, “Kotlin Appium Demo”) extentReport.setSystemInfo(“Platform”, System.getProperty(“os.name”)) extentReport.setSystemInfo(“Environment”, “QA”) } catch (e: Exception) { e.printStackTrace() } } /** * This override method used to collect current test case name add to the report * * @author sanojs * @since 01-09-2020 */ override fun onTestStart(result: ITestResult) { var testName: String = result.getMethod().getMethodName() extentTest = extentReport.createTest(testName)
  • 7. Appium Automation with Kotlin © RapidValue Solutions 7 } /** * This override method used to add pass status to the report * * @author sanojs * @since 01-09-2020 */ override fun onTestSuccess(result: ITestResult) { var testName: String = result.getMethod().getMethodName() try { extentTest.log( Status.PASS, MarkupHelper.createLabel(testName + ” Test Case PASSED”, ExtentColor.GREEN) ) } catch (e: Exception) { e.printStackTrace() } } /** * This override method used to add fail status to the report * * @author sanojs * @since 01-09-2020 */ override fun onTestFailure(result: ITestResult) { var driver: WebDriver var currentClass = result.getInstance() var testName: String = result.getMethod().getMethodName() try { driver = (currentClass as AutomationBase).getDriverInstance() var screenshotPath = Utilities().screenshotCapture(driver, result.getName()) extentTest.log( Status.FAIL, MarkupHelper.createLabel(testName + ” Test Case FAILED”, ExtentColor.RED) ) extentTest.log( Status.FAIL, MarkupHelper.createLabel(“Reason for Failure: ” + result.getThrowable().toString(), ExtentColor.RED) ) extentTest.addScreenCaptureFromPath(screenshotPath) } catch (e: Exception) { e.printStackTrace() } } /** * This override method used to add skip status to the report * * @author sanojs * @since 01-09-2020 */
  • 8. Appium Automation with Kotlin © RapidValue Solutions 8 override fun onTestSkipped(result: ITestResult) { var testName: String = result.getMethod().getMethodName() try { extentTest.log( Status.SKIP, MarkupHelper.createLabel(testName + ” Test Case SKIPPED”, ExtentColor.ORANGE) ) } catch (e: Exception) { e.printStackTrace() } } /** * This override method used to store HTML report to the specified path and flush extent report instance * * @author sanojs * @since 01-09-2020 */ override fun onFinish(testContext: ITestContext) { try { extentReport.flush() val dateFormat = SimpleDateFormat(“dd-MMM-yyyy_HH-mm-ss”) val date = Date() val filePathdate: String = dateFormat.format(date).toString() var actualReportPath: String = System.getProperty(“user.dir”) + “/AutomationReport/” + “index.html” File(actualReportPath).renameTo( File( System.getProperty(“user.dir”) + “/AutomationReport/” + “Automation_Report_” + filePathdate + “.html” ) ) } catch (e: Exception) { e.printStackTrace() } } } Step 7: Create another class called Utilities to keep common utility functions required for automation. Here, we just added one utility to capture the screenshot. Below is the code snippet to capture the screenshot, fun screenshotCapture(driver: WebDriver, fileName: String): String { var destination: String = “” try { var scrFile = (driver as TakesScreenshot).getScreenshotAs(OutputType.FILE) var dateFormat = SimpleDateFormat(“yyyyMMddHHmmss”) var cal = Calendar.getInstance() var path = File(“Failure_Screenshots”).getAbsolutePath() destination = path + “/” + fileName + dateFormat.format(cal.getTime()) + “.png” scrFile.copyTo(File(destination))
  • 9. Appium Automation with Kotlin © RapidValue Solutions 9 } catch (e: Exception) { e.printStackTrace() } return destination } Step 8: Add a testng.xml file into the project structure and map your test classes into the testng.xml to run the test cases. Once the execution is complete, the HTML report will get generated inside the AutomationReport folder in the project structure. Below is the overall project structure of Appium with Kotlin: NOTE:  Kotlin Runtime Library will automatically get added to the build path of the project when you create a Kotlin class under any package.  Kotlin class extension is .kt  The semicolon is not mandatory to end the statements in the class.  While inheriting a class from a parent class you have to declare the parent class as open, using an open keyword or you can declare the parent class as abstract using abstract. You can’t inherit a singleton class. So avoid extending the class which is declared as object in Kotlin.  If you declare a class with an object keyword then no need to create an instance. Kotlin will create an instance to access the methods or variables of that class.
  • 10. Appium Automation with Kotlin © RapidValue Solutions 10 Conclusion Kotlin is a general-purpose, open-source, statically typed programming language that combines object- oriented and functional programming features. So, Kotlin is a strong and powerful language that helps the automation engineers to write their automation script for Appium. This article aims to help the Appium automation engineers to upskill and write their scripting in a different language such as Kotlin. By, Sanoj S, Test Architect, RapidValue
  • 11. Appium Automation with Kotlin © RapidValue Solutions 11 About RapidValue RapidValue is a global leader in digital product engineering solutions including mobility, omni-channel, IoT, AI, RPA and cloud to enterprises worldwide. RapidValue offers its digital services to the world’s top brands, Fortune 1000 companies and innovative emerging start-ups. With offices in the United States, the United Kingdom, Germany and India and operations spread across the Middle-East, Europe and Canada, RapidValue delivers enterprise services and solutions across various industry verticals. Disclaimer: This document contains information that is confidential and proprietary to RapidValue Solutions Inc. No part of it may be used, circulated, quoted, or reproduced for distribution outside RapidValue. If you are not the intended recipient of this report, you are hereby notified that the use, circulation, quoting, or reproducing of this report is strictly prohibited and may be unlawful. www.rapidvaluesolutions.com/blogwww.rapidvaluesolutions.com +1 877.643.1850 [email protected]