Tips (With Code Snippets)
Appium is pretty evolving and hence there are lot of new things it supports and hence this book needs constant update. Here in this chapter, I intend to share some appium code snippets which is not necessarily explained as a separate chapter.
* Changing context while testing an app
Most of the time when you are testing an app, you will find that there is a specific page in app which is a Webview and your normal code is not working. So in those situations we need to change the application context to "WEBVIEW" or "NATIVE" accordingly. Below is a code snippet will do the same and change the context to Webview.
public static void changeDriverContextToWeb(AppiumDriver driver) {
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
if (contextName.contains("WEBVIEW"))
DriverFactory.driver.context(contextName);
}
}
A similar code can be used with Native as parameter to change the context to Native app.
public static void changeDriverContextToNative(AppiumDriver driver) {
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
if (contextName.contains("NATIVE"))
DriverFactory.driver.context(contextName);
}
}
* Starting Appium Server via code
Generally when you write an automation script you should try to write a code which runs in an un-attended mode. Starting Appium Server and killing it when the test is run is one thing which we should be handling with in the framework. Below code snippet will help you do the same. So if you notice the below code, we are using the installed appium to start the server and then the "port" on which we start is parameterized. Also we are generating an appium log file so as to capture the appium log which is again parameterized based on the device under execution.
service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
.usingDriverExecutable(new File("/Applications/Appium.app/Contents/Resources/node/bin/node"))
.withAppiumJS(new File("/Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js"))
.withIPAddress("127.0.0.1")
.usingPort(port)
.withLogFile(new File("target/"+deviceUnderExecution+".log")));