Getting started with AWS Device Farm and Selenium WebDriver
Tags: seleniumwebdriver, testautomationtools, softwaretesting, aws
Published: 2020-11-20 17:02:47

**AWS Device Farm** is a testing service from AWS that can help us to improve the quality of our web and mobile applications by testing them across a wide range of desktop browsers and real mobile devices without the need to deploy and manage a test infrastructure. 

The service allows us to run our tests on multiple desktop browsers or real devices to speed up the execution of your test suite and generates videos and logs to help you quickly identify problems with your application.

## AWS Device Farm Desktop
previously we can use AWS Device Farm for mobile testing only but now we have an option to use it for running our Selenium tests on multiple desktop browsers hosted on AWS. The feature scales seamlessly so you can run your tests in parallel on multiple browser instances to speed up the execution of your test suite.

For every browser the test is executed on, Device Farm generates video recordings and Selenium logs to help you quickly identify any issues with your web app.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/glj25wxh52h4ltnpui6n.png)

In the next steps, we will know how to how to use AWS Device Fram with Selenium WebDriver:

### Pre-requisites:

- macOS
- IntelliJ IDEA
- Install AWS CLI, check the following link to know more about this step from AWS documentation https://docs.aws.amazon.com/cli/latest/userguide/install-macos.html

- After installing AWS CLI you need to configure your account with the command `aws configure`

**You need to add the following credentials:**

- AWS Access Key ID
- AWS Secret Access Key
- Default region name - for example `us-west-2`

To know more about your Security Credentials you can check this link

https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html


## Create AWS Device Fram Project
1- Log in with your AWS account https://console.aws.amazon.com/
2- Goto AWS Device Farm page
3- Click on **Desktop browser testing** projects

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tcaalr0y9mbu8gjy9vt6.png)

4. Click on Create a new project with the name SeleniumAWS and click on Create project
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ku72lb0nn8nsvoptv0oy.png)


5- After creating the project successfully you need to copy the ARN (Amazon Resource Name) of the project and save it because we will need it in our code.

### Prepare the Selenium Project
1- Open IntelliJ and create a maven project and name it **SeleniumAWSDeviceFarm** as the following images

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qcb3v8z4w62ks0i0d7s7.png)


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6l00atstbs7ru0v65106.png)

Don't forget to click on the **Enable Auto Import** link for adding the maven dependencies

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k0cn5r5f45tvdr150s7w.png)

2- Add the following maven dependencies in the `POM.xml` file

```xml 
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.1.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>devicefarm</artifactId>
        <version>2.10.52</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-remote-driver</artifactId>
        <version>3.141.59</version>
    </dependency>
</dependencies> 

```

3- Create a new Java Class with the name `SeleniumDeviceFarm`

4- Add the `RemoteWebDriver` in the class level

`private static RemoteWebDriver driver;`

5- Add the following setup() void with @BeforeTest TestNG annotation

```java
@BeforeTest
void setUp() throws MalformedURLException {

    String projectARN = "YOUR PROJECT ARN HERE";
    DeviceFarmClient client  = DeviceFarmClient.builder()
            .region(Region.US_WEST_2)
            .build();
    CreateTestGridUrlRequest request = CreateTestGridUrlRequest.builder()
            .expiresInSeconds(200)
            .projectArn(projectARN)
            .build();
    CreateTestGridUrlResponse response = client.createTestGridUrl(request);
    URL testGridUrl = new URL(response.url());
    driver = new RemoteWebDriver(testGridUrl, DesiredCapabilities.chrome());
}
```

In the previous code, we started a connection with our project using AWS SDK for Java by creating a new test in our project after that from the response we get the remote grid URL to add it to our remote driver with desired capabilities (Chrome browser in our case).

Now we are ready to write our test script

```java
@Test
public void userLogin()
{
    driver.manage().window().maximize();
    driver.navigate().to("https://the-internet.herokuapp.com/login");
    driver.findElement(By.id("username")).sendKeys("tomsmith");
    driver.findElement(By.id("password")).sendKeys("SuperSecretPassword!");
    driver.findElement(By.className("radius")).click();
    Assert.assertTrue(driver.getCurrentUrl().contains("secure"));
}
```

And don't forget to add a teardown and quite the driver.


```java

@AfterTest
void tearDown() {
    driver.quit();
}
```

And the full code will be like:

```java
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.devicefarm.*;
import software.amazon.awssdk.services.devicefarm.model.*;

import java.net.MalformedURLException;
import java.net.URL;

public class SeleniumDeviceFarm
{
    private static RemoteWebDriver driver;

    @BeforeTest
    void setUp() throws MalformedURLException {

        String myProjectARN = "YOUR PROJECT ARN HERE";
        DeviceFarmClient client  = DeviceFarmClient.builder()
                .region(Region.US_WEST_2)
                .build();
        CreateTestGridUrlRequest request = CreateTestGridUrlRequest.builder()
                .expiresInSeconds(300)
                .projectArn(myProjectARN)
                .build();
        CreateTestGridUrlResponse response = client.createTestGridUrl(request);
        URL testGridUrl = new URL(response.url());
        driver = new RemoteWebDriver(testGridUrl, DesiredCapabilities.chrome());
    }

    @Test
    public void userLogin()
    {
        driver.manage().window().maximize();
        driver.navigate().to("https://the-internet.herokuapp.com/login");
        driver.findElement(By.id("username")).sendKeys("tomsmith");
        driver.findElement(By.id("password")).sendKeys("SuperSecretPassword!");
        driver.findElement(By.className("radius")).click();
        Assert.assertTrue(driver.getCurrentUrl().contains("secure"));
    }

    @AfterTest
    void tearDown() {
        driver.quit();
    }
}
```

We can now run the test and check if the configuration is correct or not.

If everything is OK we can open the project on the Device Farm page and check the selenium session and also you can check the logs and the recorded video as the following images.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q90dr0bko51w0dp0p863.png)


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zzpszq6y6rsiyqgqn5eh.png)


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vzbbfnt2nff3r1h7h49o.png)


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/czx1g92r0tmonp4jtuqn.png)

And for sure you can integrate it with any CI server to running your tests continuously.

### Reference
https://aws.amazon.com/device-farm/

Thank you for reading

Good luck and Happy testing!

Moataz Nabil