How To Automate Screen Recording In Appium

In this article, we will learn why we need to automate screen recording in Appium and how to automate screen recording in Appium mobile automation framework.

What is Appium?

Appium is an open-source mobile automation framework that aims to support the automation of native, hybrid and web apps on different platforms like Android, iOS and Windows.

Why do we need to automate screen recording in Appium?

Most of the time, while doing test suite execution, a few tests fail, and to debug that, we need to check the logs or screenshots first. What if we get the recording of failed tests and by going through these we can identify at what step the test case failed, was it because of locator change, due to network issue, or any other issue?

Platforms like SauceLabs and BrowserStack use video recording APIs to provide the recordings of the execution result. In this article, we will see how we can capture recordings on our local machine.

How To Use ScreenRecorder

  1. Open IDE and open maven project.
  2. Navigate to the pom.xml file and add the below dependency in the file under <dependencies></dependencies> tag.
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

The Apache Commons Codec package contains simple encoders and decoders for various formats such as Base64 and Hexadecimal.

3. Create a class and add the static imports.

import io.appium.java_client.screenrecording.CanRecordScreen;
import org.apache.commons.codec.binary.Base64;

4. Create a method named StartRecording() in the test class. This method will contain the logic to start the recording.

public void startRecording()
 {
        ((CanRecordScreen)webDriver).startRecordingScreen();
 }

CanRecordScreen is an interface that extends another interface ExecutesMethod. This interface has the method startRecordingScreen() that Starts the asynchronous screen recording process with default options.

5. Create a new method StopRecording() to contain the logic to stop recording.

Scenario: Follow below mentioned steps to write the logic.

2.1) Record Base64 encoded content and store it in String format.
2.2) Define the path to store the recorded video.
2.3) Open a FileOutputStream
2.4) Store the recorded media in mp4 format.
2.5) Add a timestamp with the videos.
2.6) Write and close the Output Stream.

private static String timestamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()).replaceAll(":", "-");
String media = ((CanRecordScreen) webDriver).stopRecordingScreen();
String dirPath =   System.getProperty("user.dir")+"/Videos";
  
   File videoDir = new File(dirPath);
   FileOutputStream stream = null;
try {
 stream = new FileOutputStream(videoDir + File.separator +timestamp+ ".mp4");
            stream.write(Base64.decodeBase64(media));
            stream.close();
            
        } catch (Exception e) {
            
        } finally {
            if(stream != null) {
                stream.close();
            }
        }

In the above script, we passed the web driver object and called the stopRecordingScreen() method. This method Gathers the output from the previously started screen recording to a media file with default options and Returns: The base-64 encoded content of the recorded media file.

Complete Code

Refer to the below code snippet for the full working code after the successful addition of the logic to start and stop recording the screen using the common-codec utility.

public class AndroidRunner {
    public AndroidDriver<MobileElement> wd = null;
    static AppiumDriverLocalService service;
    private static String timestamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()).replaceAll(":", "-");


    @BeforeSuite
    public void startappium()
     {
        service = AppiumDriverLocalService.buildDefaultService();
        service.start();
     }


  @BeforeTest
  public void setup() {
     DesiredCapabilities capabilities = new DesiredCapabilities();
     capabilities.setCapability("platformName", "Android");
     capabilities.setCapability("appPackage", "com.walkwithme");
     capabilities.setCapability("appActivity", "walkwithme.MainActivity");
     capabilities.setCapability("deviceName", "Android");
     capabilities.setCapability("app",System.getProperty("user.dir")+"PathToApk");

 try {
 wd = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"),capabilities);
    startRecording();
     }catch(Exception e) {
       e.printStackTrace();
      }
    }
    
    public void startRecording() throws MalformedURLException {
        ((CanRecordScreen)wd).startRecordingScreen();
    }
    
    public void stopRecording() throws IOException {

       String media = ((CanRecordScreen) wd).stopRecordingScreen();
       String dirPath =   System.getProperty("user.dir")+"/Videos";
       File videoDir = new File(dirPath);
       FileOutputStream stream = null;
       
    try {
      stream = new FileOutputStream(videoDir + File.separator +timestamp+ ".mp4");
            stream.write(Base64.decodeBase64(media));
            stream.close();

        } catch (Exception e) {

        } finally {
            if(stream != null) {
                stream.close();
            }
        }
    }

    @Test
    public void applicationrunb() throws Throwable {
      System.out.println("HELLO App launched");
     wd.findElementByClassName("android.widget.EditText").sendKeys("hello");
     }

    @AfterTest
    public void stopappium() throws IOException {
        stopRecording();
        wd.quit();
    }

    @AfterSuite
    public void closeservice() {
        service.stop();
    }
}

In the code snippet, we have started the appium server using code and set up the desired capabilities for the session creation. Once the session is established successfully then start the recording function start recording the mobile device screen and store the recorded video on the provided path.

Now Execute the Script, Refresh and check the videos folder. MP4 file should be there.

Enable Screen Recording In Appium

Conclusion

In this post, we have learned to automate screen recording in the Appium test automation framework. This approach works perfectly with Appium 1. x versions. You can refer to the appium 2.0 article for the enhancements. Refer to the official documentation for more information.

Leave a Reply

Discover more from AutomationQaHub

Subscribe now to keep reading and get access to the full archive.

Continue reading