Appium is an open-source automation tool, known for testing mobile apps across various platforms. In the last article, we have seen how we can start with Appium 2.0. In this post, we will learn different ways to start Appium server Programmatically using Java.
Advantages of Appium Server Automation
Generally, we start the appium server using the command line, open the emulator or real device and execute our test automation suite. This process can be automated and it provides several benefits. Some of them are listed below:
- CI/CD Integration: Controlling the Appium server through programming allows us to automate the entire testing environment. This helps us in running our tests on a continuous integration (CI) server or as part of an automated testing pipeline.
- Resource Management: We can manage our system’s resources by starting and stopping the Appium server as needed within the code. The server will run only when necessary, decreasing resource consumption when tests are not actively being executed. This can result in more efficient use of computational resources.
- Dynamic Port Allocation: Some tests might require running multiple instances of the Appium server simultaneously, each on a different port. Programmatically starting the server gives us the ability to allocate free ports dynamically, preventing port conflicts and enabling parallel test execution.
- Cleanup and Resource Release: Starting and stopping the server through code helps in ensuring the proper cleanup of resources.
Steps To Start Appium Server Programmatically
Step 1: Install Appium:
Before initiating the Appium server programmatically, ensure that you have Appium installed on your system. You can install Appium via npm (Node Package Manager) using the following command:
npm install -g appium
Step 2: Set Up Dependencies:
Depending on our testing requirements, we may need to install additional dependencies such as Node.js, Java Development Kit (JDK), Android SDK, Xcode (for iOS testing), etc. Ensure all necessary dependencies are installed and configured correctly.
Step 3: Start the Appium Server:
There are multiple ways to start the Appium server through code. A few of them are listed in the below section.
1) By Using AppiumDriverLocalService Class
The AppiumDriverLocalService class is a final class in the Appium Java Client library that extends the DriverService class. With the help of this class, we can start, stop, and configure the Appium server directly from our Java code.
AppiumDriverLocalService service = AppiumDriverLocalService.buildDefaultService();
buildDefaultService() is the static method of the AppiumDriverLocalService class. The above statement indicates that an instance of the AppiumDriverLocalService class was created with the default configuration. While using this static method make sure that the appium command is in the system’s PATH.
Code Snippet:
@BeforeSuite
public void startappium()
{
AppiumDriverLocalService service =AppiumDriverLocalService.buildDefaultService();
service.start(); //Starts the Appium Server
}
@AfterSuite
public void closeservice()
{
service.stop(); //Stops the Appium server
}
This method is useful when we want to start the Appium server quickly with minimal configuration. This class has other useful methods, if we want to check if the server is running or stopped then we can use the below code.
boolean isRunning = service.isRunning();
This method will return ‘true’ if the Appium server is running else return ‘false’.
If we want to check the host address of the Appium server then we can fetch it using the ‘getAddress()’ method.
String hostAddress = service.getAddress();
2) By Using AppiumServiceBuilder
AppiumServiceBuilder is also a final class of Appium API that extends a static builder class. This class is very useful when we require more control over the server’s configuration.
AppiumServiceBuilder class gives us full control to customize the Appium server’s behaviour and configuration. We can configure the server address, desired port, and desired capabilities using this class.
AppiumServiceBuilder serviceBuilder = new AppiumServiceBuilder();
Create an instance of the AppiumServiceBuilder class. Then use the withAppiumJS method which takes the path of “main.js” as an argument. Next, we need to define the server address using with IP address () method.
serviceBuilder.withAppiumJS(new File("Path to main.js file"))
.withIPAddress("127.0.0.1").usingPort(4723).withTimeout(Duration.ofSeconds(200))
.build().start();
main.js file is responsible for the invocation of the Appium server. This file will be present under the node_modules section.
windows path : Users/YourUserName/AppData/Roaming/npm/node_modules/appium/build/lib/main.js
MAC path : /usr/local/lib/node_modules/appium/build/lib/main.js
The above code can be customized as per the requirement. If we do not want to use the default port and require the Appium server to start at any available port then can use the below-mentioned code. This way, if I have a forgotten Appium server running in another window, it won’t interfere with my tests.
serviceBuilder.withAppiumJS(new File("/usr/local/lib/node_modules/appium/build/lib/main.js"))
.withIPAddress("127.0.0.1").usingAnyFreePort().withTimeout(Duration.ofSeconds(200)).build().start();
To prevent the timeout we can add a wait condition. Refer to the below code.
package com.appium2;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import java.io.File;
import java.net.URL;
import java.time.Duration;
public class androidRunner {
public AndroidDriver wd = null;
static AppiumDriverLocalService service;
AppiumServiceBuilder serviceBuilder = new AppiumServiceBuilder();
@BeforeTest
public void setup()
{
serviceBuilder.withAppiumJS(new File("/usr/local/lib/node_modules/appium/build/lib/main.js"))
.withIPAddress("127.0.0.1").usingPort(4723)
.withTimeout(Duration.ofSeconds(200))
.build().start();
UiAutomator2Options capabilities = new UiAutomator2Options();
capabilities.setPlatformName("Android")
.setAutomationName("UIAutomator2")
.setAppPackage("com.swaglabsmobileapp")
.setAppActivity("com.swaglabsmobileapp.MainActivity")
.setApp(System.getProperty("user.dir")+"/src/test/resources/SauceLabsMobile.apk");
try {
wd = new AndroidDriver(new URL("http://0.0.0.0:4723/"),capabilities);
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Test
public void applicationrunb() throws Throwable
{
wd.findElement(By.xpath("android.widget.EditText")).sendKeys("hello");
}
@AfterTest
public void closeservice()
{
serviceBuilder.build().stop();
}
}
Launch the virtual device and then execute this code. You can see on the console that the Appium server has started with provided desired capabilities and flags.
Conclusion
Initiating the Appium server programmatically allows developers and testers to automate the setup process, increasing productivity and consistency in mobile application testing.