Record Selenium Automation Flows

BEST-AUTOMATION-TESTING-TOOLS

         We know that automation testing entirely relies on the pre-scripted test which runs automatically to compare actual results with the expected results. This helps the tester to determine whether or not an application performs as expected. Automation testing helps to reduce the effort of the regression test suite execution of manual testers.

         Everyone is familiar with Selenium test automation for Web application and the test automation framework has the capability to generate the reports in different formats like HTML, PDF. Also, the frameworks will generate a screenshot of the UI when a test fails that depends on the configuration in the Automation Listeners. In this article I would like to share the concept of video record your automation flows; even if the test case pass or fail or skip that again depends on your configuration in the Automation Listeners.

Who will help you to record video?

         Selenium has no built-in capability to record the video of the automation flow. Here I am recording the Selenium automation flow with the help of Monte Screen Recorder Java library. The Monte media library used for processing media data. Supported media formats include still images, video, audio, and meta-data. You can record your entire automation flows for future references to share the flow as a demo to your client

Why do we need a video recording?

Video recordings of Selenium test case execution can play a major role. Not only would these help in debugging issues more efficiently, but we can also use recorded videos to show test execution activities to the client or other stakeholders. Additionally, these recorded videos can be added into the project management or defect management tool while creating bugs, which helps in understanding the bug clearly.

How can we achieve the video recording?

Pre-requisites:

  • Create a Maven project.
  • Add following dependencies in pom.xml file:
    • testng
    • selenium-java
    • selenium-server
    • monte-screen-recorder (you will get it from maven repository)
  • Write sample test cases in a test class.
  • Create VideoRecordingUtility class and extends ScreenRecorder class of Monte Recorder library.

       ScreenRecorder class records mouse clicks occurring on other Java Windows running in the same JVM. Mouse clicks occurring in other JVM’s and other processes are not recorded. This ability is useful for performing in JVM recordings of an application that is being tested. This recorder uses four threads. Three capture threads for screen, mouse cursor and audio, and one output thread for the movie writer. ScreenRecorder class is a powerful class with many useful methods, here I am using two important methods of ScreenRecorder class which is start and stop. start method helps to record the screen with a defined type (in this example the type is AVI). stop method helps to stop the screen recording. Here I have created two custom methods startRecording and stopRecording. startRecording method having an argument which included in the name of the video file. You can create an object of ScreenRecorder and call start and stop methods using that object.

Following are the actual logic implementation inside startRecording method:

public static void startRecording(String methodName) throws Exception {
File file = new File(“./AutomationVideoReports/”);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width;
int height = screenSize.height;
Rectangle captureSize = new Rectangle(0, 0, width, height);
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
screenRecorder = new VideoRecordingUtility(gc, captureSize,
new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE, DepthKey, 24, FrameRateKey,
Rational.valueOf(15), QualityKey, 1.0f, KeyFrameIntervalKey, 15 * 60),
new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, “black”, FrameRateKey, Rational.valueOf(30)),
null, file, methodName);
screenRecorder.start();
}

Following are the actual logic implementation inside stopRecording method:

public static void stopRecording() throws Exception {
screenRecorder.stop();
}

        The video recording will store in AutomationVideoReports folder. You can use startRecording and stopRecording methods based on your convenience in automation listener class, if you are using TestNG framework then you can implement ITestListener interface and use startRecording and stopRecording inside the implemented methods of ITestListener to record the video of entire test suite flow or record pass/fail/skip cases. Try to use the above logic to record your selenium automation flows and enjoy your automation.

make it perfect!

Start IEDriver with the latest Selenium

Blog-image

      Recently, one of my colleagues encountered an issue in Internet Explorer during the automation using the latest selenium (3.141.59). Issue related to interacting web objects in IE. Driver instantiation was successful but failed to do actions in the web objects. Later, found a solution to solve this issue with the help of setting different capabilities especially ignoreProtectedModeSettings as true. Following latest IE driver initiation logic which solved the above issue,

WebDriver driver;
InternetExplorerOptions ieCapabilities = new InternetExplorerOptions();
ieCapabilities.setCapability(“nativeEvents”, false);
ieCapabilities.setCapability(“unexpectedAlertBehaviour”, “accept”);
ieCapabilities.setCapability(“ignoreProtectedModeSettings“, true);
ieCapabilities.setCapability(“disable-popup-blocking”, true);
ieCapabilities.setCapability(“enablePersistentHover”, true);
ieCapabilities.setCapability(“ignoreZoomSetting”, true);

InternetExplorerDriverService service = new InternetExplorerDriverService.Builder()
.usingDriverExecutable(new File(“path to your IEDriverServer.exe”))
.usingAnyFreePort().build();
driver = new InternetExplorerDriver(service, ieCapabilities);

Please try to use the above code snippet from your end if you are facing the same kind of issue.

make it perfect!

Parallel Test Executions in Automation – TestNG and NUnit

cross_platform

      One day I got an opportunity to automate an application using both Selenium Java and Selenium C#, that was the specific requirement of the customer to do it on both Java and C#. Later customer said to execute different test cases from different class in different browsers in parallel mode. Their aim was to complete the execution of all test cases in a minimum amount of time. Here, I would like to share how I achieved the parallel execution in both Selenium Java and Selenium C#.

Parallel Execution in Selenium Java Automation:

       In case of Selenium Java, I used TestNG’s parallel execution capability with support of attribute parallel=”tests” along with the tag in TestNG XML. I have created two tags to launch two different driver instances. Following is the sample testng.xml which I used for parallel execution:

<suite name=”TestSuite” parallel=”tests” preserve-order=”true”>
<test name=”Test In Google Chrome”>
<parameter name=”browserName” value=”Chrome”/>
<classes>
<class name=”com.test.TestSuiteClassSmoke”/>
</classes>
</test>
<test name=”Test In Firefox”>
<parameter name=”browserName” value=”Firefox”/>
<classes>
<class name=”com.test.TestSuiteClassSanity”/>
</classes>
</test>
</suite>

      In the above testng.xml file, contains one test to run all the test cases of the Smoke Suite in Google Chrome browser and the second test to run all the test cases of the Sanity Suite in Firefox. Both browser instances are start same time and execute in parallel. TestSuiteClassSanity and TestSuiteClassSmoke classes extends AutomationBase class to get the driver instances for execution. Following is the actual implementation of AutomationBase class:

@BeforeClass()
@Parameters({“browserName”})
public void SetUp(String browserName) throws IOException, InterruptedException
{
try {
if(browserName.equalsIgnoreCase(“chrome”)){
// implement code to start chrome driver session
}
else if(browserName.equalsIgnoreCase(“firefox”)){
// implement code to start firefox driver session
}
}catch (Exception e) {
e.printStackTrace();
}
}

Parallel Execution in Selenium C# Automation:

      In case of Selenium C#, there is no direct capability like TestNG to achieve the parallel execution of test cases in different instances of browsers. I used NUnit attributes just above in all test classes and that test class extends AutomationBase class. Used following NUnit attributes:

  • [TestFixture(“chrome”)]
  • [TestFixture(“firefox”)]
  • [Parallelizable]

        Added a parameterized constructor (the parameter should be browserName) and call StartBrowser(browserName) method inside the constructor. StartBrowser (browserName) method is implemented in AutomationBase class. Following is the sample implementation that I have done in the test class:

using NUnit.Framework;
namespace com.test.testcases
{
[TestFixture(“chrome”)]
[TestFixture(“firefox”)]
[Parallelizable]
public class TestModuleClass: AutomationBase
{
public TestModuleClass(string browserName)
{
StartBrowser(browserName);
}

[Test, Order(1)]
public void TC_001_SampleTest()
{
//Your test steps
}
}
}

    In AutomationBase class, I have added new method StartBrowser(String browserName) to identify the requested browser for execution and implemented the logic to drive chrome and firefox drivers. Following is the implementation of StartBrowser,

public IWebDriver StartBrowser(String browserName)
{
try
{
if (browserName.ToLower().Equals(“”))
{
throw (new Exception(“BROWSER_NAME is not specified”));
}
if (browserName.ToLower().Equals(“chrome”))
{
// implement code to start chrome driver session
}
if (browserName.ToLower().Equals(“firefox”))
{
// implement code to start firefox driver session
}
}
catch (Exception e)
{
throw (e);
}
return driver;
}

     You can try above mechanisms of parallel executions in automation for both Selenium Java and Selenium C#.

make it perfect !

Selenium Automation using C# (NUnit)

DYLSVhtWAAA5qn9seleniumwithC

     In the previous post, we discussed about Selenium C# and MSTest framework. Another day, I got an opportunity to write selenium automation using C# language and NUnit framework. Prior to scripting, I started the configuration from the scratch to achieve my selenium scripting using C# and NUnit. Here I would like to share my experience with configuration and scripting part,

Steps for install and configure Visual Studio:

Step 1: Navigate to the URL https://www.visualstudio.com/downloads/ and Click on the ‘Free download’ button displayed on Visual Studio Community 2017 tab.
Step 2: Open the exe downloaded. Click on ‘Yes’ if asked for Admin Rights.
Step 3: A popup will appear. Click on ‘Continue’ button.
Step 4: In the next screen, select the check-boxes for

  • Universal Windows Platform development
  • .Net desktop development

Click on ‘Install.’ Wait for installation of each component to complete. Files are 16GB in size and will take time.
Step 5: A pop up will be displayed. Click on ‘Restart’ button (if required).
Step 6: Once the machine is restarted, search for “Visual Studio 2017” on the start menu and click on the search result. In the next screen, Click on “Not now, maybe later” link if you do not have an existing account.
Step 7: In the next screen,

  • Select color theme of your liking
  • Click the button “Start Visual Studio'”

Step 8: Visual Studio ‘Get Started’ screen will appear.

Set up Visual Studio with Selenium WebDriver:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “Selenium”.
  2. Select the first search result “Selenium.WebDriver”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click on ‘Install’.
  6. Select second search result “Selenium.Support”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Set up Visual Studio with NUnit Framework:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “NUnit”
  2. Select the search result “NUnit”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click Install.
  6. In the same window, select search result “NUnit3TestAdapter”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Create a new project in Visual Studio:

Step 1: In the File Menu, Click New > Project
Step 2: In the next screen,

  1. Select the option ‘Visual C#’
  2. Click on Console App (.Net Framework)
  3. Enter project name.
  4. Click OK

Step 3: You will be able to see the created project.

     Now the configurations and project is ready, next you can add one C# class file to project and start writing your first script for automation as below. I used this class file to start my C# scripting for selenium automation,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using System.Threading;

namespace seleniumTestProject
{
[TestFixture]
public class SeleniumTest
{
public IWebDriver driver; //declare the driver object

[OneTimeSetUp]
public void BeforeClass()
{
driver = new ChromeDriver(“path_to_chromedriver.exe”); //initialize the ChromeDriver instance
driver.Url = “https://www.google.co.in/&#8221;; //load application URL
}

[SetUp]
public void BeforeTest()
{
//You can write any precondition to perform prior to each test cases
}

[Test]
public void GoogleSearchTest()
{
driver.FindElement(By.Id(“lst-ib”)).SendKeys(“Journey of Quality”);
}

[TearDown]
public void AfterTest()
{
driver.Close();
}

[OneTimeTearDown]
public void AfterClass()
{
driver.Quit();
}
}
}

     Try the above configuration and scripting using C# for Selenium Automation from your end. I recommend everyone to use NUnit framework than MSTest framework for Selenium C# scripting. NUnit provides straight-froward scripting when use their annotations. In case of MSTest, we must declare the method as static and should possess one parameter when use [AssemblyInitialize] or [ClassInitialize]. In case of NUnit, no need to declare the method as static when uses [OneTimeSetUp] or [SetUp].

make it perfect !

 

How to fetch DRIVER_EXE_PROPERTY for different browsers dynamically?

1_6KbvW_GQYI9u6Cc_S2AHLQ@2x

   In case of Selenium Automation for Web application, most of the time people needs to set DRIVER_EXE_PROPERTY in the code level prior to driver instantiation. For that we need to download the respective DRIVER_EXE and set the path of the DRIVER_EXE in the code.

  Here my piece of code explain how to fetch DRIVER_EXE_PROPERTY automatically while script execution for different browsers. I have done it for chrome, Firefox and IE in Windows system as well as chrome and Firefox in MAC system. Following are the details:

  Below code is necessary to instantiate chrome driver session. In this code I used  getWebAutomationDriver(browserName) to get the DRIVER_EXE path from the system.

System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, getWebAutomationDriver(browserName));
ChromeDriverService chromeservice = new ChromeDriverService.Builder().build();
driver = new ChromeDriver(chromeservice); 

Following is the explanation for getWebAutomationDriver(browserName) method and there again we called  getActualDriverPath(browserName) as a private method to get the actual DRIVER_EXE path,

public static String getWebAutomationDriver(String browserName) throws InterruptedException {
String driverPath = null;
final String operatingSystem = System.getProperty(“os.name“);
try {
if (getActualDriverPath(browserName) == null) {
if (operatingSystem.contains(“Windows”)) {
if (browserName.equalsIgnoreCase(“chrome”)) {
System.out.println(
“chromedriver not installed on system, go to command-line and enter ‘npm install chromedriver’. \nAlso set PATH variable ‘C:\\Users\\…..\\node_modules\\chromedriver\\lib\\chromedriver’ in your system.\nOnce it done, you may need to restart your system”);
System.exit(0);
}
if (browserName.equalsIgnoreCase(“Firefox”)) {
System.out.println(
“geckodriver not installed on system, go to command-line and enter ‘npm install geckodriver’. \nAlso set PATH variable ‘C:\\Users\\…..\\node_modules\\geckodriver’ in your system.\nOnce it done, you may need to restart your system”);
System.exit(0);
}
if (browserName.equalsIgnoreCase(“IE”) || browserName.equalsIgnoreCase(“Internet Explorer”)
|| browserName.equalsIgnoreCase(“InternetExplorer”)) {
System.out.println(
“iedriver not installed on system, go to command-line and enter ‘npm i iedriver@3.7.0’. \nAlso set PATH variable ‘C:\\Users\\…..\\node_modules\\iedriver\\lib\\iedriver64’ in your system.\nOnce it done, you may need to restart your system”);
System.exit(0);
}
} else {
if (browserName.equalsIgnoreCase(“chrome”)) {
System.out.println(
“chromedriver not installed on MAC, go to terminal and enter ‘brew install chromedriver’. \nAlso set PATH variable in Run Configurations of your project. \nSteps: Right click on your project > Run As > Run Configurations > Environment tab”);
System.exit(0);
}
if (browserName.equalsIgnoreCase(“Firefox”)) {
System.out.println(
“geckodriver not installed on MAC, go to terminal and enter ‘brew install geckodriver’. \nAlso set PATH variable in Run Configurations of your project. \nSteps: Right click on your project > Run As > Run Configurations > Environment tab”);
System.exit(0);
}
}
} else {
driverPath = getActualDriverPath(browserName);
}
} catch (Exception e) {
e.printStackTrace();
}
return driverPath;
}

    Following is the explanation for getActualDriverPath(browserName) to fetch the actual DRIVER_EXE path,

private static String getActualDriverPath(String browserName) {
String actualDriverPath = null;
try {
String command = null;
final String operatingSystem = System.getProperty(“os.name“);
if (operatingSystem.contains(“Windows”)) {
if (browserName.equalsIgnoreCase(“chrome”)) {
command = “where ” + “chromedriver”;
}
if (browserName.equalsIgnoreCase(“Firefox”)) {
command = “where ” + “geckodriver”;
}
if (browserName.equalsIgnoreCase(“IE”) || browserName.equalsIgnoreCase(“Internet Explorer”)
|| browserName.equalsIgnoreCase(“InternetExplorer”)) {
command = “where ” + “IEDriverServer”;
}
} else {
if (browserName.equalsIgnoreCase(“chrome”)) {
command = “which ” + “chromedriver”;
}
if (browserName.equalsIgnoreCase(“Firefox”)) {
command = “which ” + “geckodriver”;
}
}
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = “”;
while ((line = reader.readLine()) != null) {
actualDriverPath = line;
break;
}
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
return actualDriverPath;
}

   Try to use above methods to get the DRIVER_EXE path automatically into your automation script.

make it perfect !