Start Appium server programmatically

Shiv Jirwankar
2 min readDec 11, 2020

--

Have you ever felt tired to make sure that the Appium Desktop server is up and running before executing your tests? I have found this very annoying to always manually check the Appium server status by going through the Appium desktop app or in some case from the command line.

But we can easily get rid of the manual start of the server. All these actions will now be handled from the code itself. Here’s what needs to be done.

We will use ‘AppiumDriverLocalService’ class to start and stop the Appium server.

Start server at default port with the default settings

To start the Appium server at the default URL and at default settings, use ‘buildDefaultService()’ method.

Example:

AppiumDriverLocalService service = AppiumDriverLocalService.buildDefaultService();

service.start(); //to start the Appium Server

service.stop(); //to stop the Appium Server

Start server at desired port and settings

We will use the ‘AppiumServiceBuilder’ class to build the service and will then pass its reference as an argument to ‘AppiumDriverLocalService’.

‘AppiumServiceBuilder’ has a bunch of methods by which we can configure what kind of server we want to have. Let’s cover those methods first.

AppiumServiceBuilder builder = new AppiumSeriveBuilder();

To start the Appium server at your desired IP and port number,

builder.IPAddress(“127.0.0.1”).usingPort(4728);

To start the Appium server at any random free port,

builder.usingAnyFreePort();

Define the location of Node.js and Appium package

In order to run the Appium server programmatically from AppiumServiceBuilder, it needs to know the location of Node.js executable and also the Appium package on the system.

builder.usingDriverExecutable(new File(“/path/to/node/executable”)); builder.withAppiumJS(new File(“/path/to/appium”));

Instead of passing the above locations as hard-coded values, we can also define those as environment variables. In this way, there will be no conflicts if ever you are running your test cases on any machine or CI environment. Create two environment variables by the name APPIUM_PATH and NODE_PATH and define their respective locations.

HashMap<String, String> env = new HashMap();

env.put(“PATH”, “/usr/local/bin:” + System.getenv(“PATH”)); builder.withEnvironment(environment);

System.env(“PATH”) will return the value of the specified environment variable “PATH”.

So far we have successfully able to start the Appium server at a random free port. But here’s a catch, we also need to define the same port while initializing the driver. To handle this scenario, we can use the method of AppiumDriverLocalService.

service.getUrl()

This will return the URL and port number at which the server got started.

Full code

--

--