Thursday, 31 March 2016

Hightlighting or focusing a web element in Selenium using Javascript

Agenda of this blog: To discuss about how to highlight/focus an web element using using JavaScript in Selenium WebDriver.

What is the need: Sometimes its very useful to highlight webelement before performing any web-actions on it so that we can get an idea on which element we are performing the specific action.

Here is the code snippet which high lights a web element field using Javascript.



           
                                   
            public static void setHighlight(WebElement element)
            {
                                    String attributeColourvalue = "border:3px solid green";
                                    JavascriptExecutor executor = (JavascriptExecutor) driver;
                                    String getAttribute = element.getAttribute("style");
                                    executor.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, attributeColourvalue);
                                    try
                                    {
                                                Thread.sleep(100);
                                    }
                                    catch (InterruptedException e)
                                    {
                                                System.out.println("Sleep interrupted - "+e);
                                    }
                                    executor.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, getAttribute);
                             
            }


Visit for More Automation Related Discussion:

https://www.youtube.com/channel/UCKSk4gkmO3LXcW17hFUkmcQ/videos






How to enter text in Selenium using Javascript

Agenda of this blog: To discuss about how to enter text(sendkeys alternative in Selenium) on any web input field using JavaScript in Selenium WebDriver.

What is the need: Sometimes we need to use Javascript in performing some of the web actions as in some cases those web elements does behave sporadically with normal selenium script.

Here is the method which enters the text on web input field using  Javascript.



           
            public void  javaScriptType(WebDriver driver,By locator,String textToBeEntered){
                        try{
                                    WebElement element=driver.findElement(locator);
                                    ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('value', '"+textToBeEntered+"');",element);
                        }
                        catch(NoSuchElementException ex){
                                    Assert.fail("Element "+locator+" was not found in DOM "+ex);
                        }
                        catch(Exception ex){
                                    Assert.fail("Exception Occured while entering text using JavaScript: "+ex);
                        }
            }



Visit for More Automation Related Discussion:


https://www.youtube.com/channel/UCKSk4gkmO3LXcW17hFUkmcQ/videos






How to click on WebElements in Selenium using JavaScript

Agenda of this blog: To discuss about how to click on any Web Element using JavaScript in Selenium WebDriver.

What is the need: Sometimes we need to use Javascript in performing some of the web actions as in some cases those web elements does behave sporadically with normal selenium script.

Here is the code snippet which performs the click operation on webelement using Javascript.


public void javaScriptClick(WebDriver driver,By locator){
                        try{
                        WebElement element=driver.findElement(locator);
                        ((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
                        }
                        catch(NoSuchElementException ex){
                       
                        Assert.fail("Element " + locator + " was not found in HTML DOM- NoSuchElementException"+ ex.getMessage());
                       
                        }
                       
                        catch(Exception e){
                                    Assert.fail("Exception occured : "+e.getMessage());
                        }
            }

            
Visit for More Automation Related Discussion:


https://www.youtube.com/channel/UCKSk4gkmO3LXcW17hFUkmcQ/videos





Thursday, 17 March 2016

Re-running the failed test script using JUnit


Agenda of this blog: To discuss about how to re-run your failed automation scripts without any manual interference using JUnit- Unit test framework.

What is the need: When you write your automation script it might happen that some of your test script may get failed due any reason, it might be due to some internet issues, or UI issues or locator changes or might be some issue with the coding itself or some sporadic issues. So in that case we may need to re-run the failed test case without triggering those again manually. This feature is supported by your Unit test framework TestNg/JUnit, here we will be discussing considering the JUnit as the Unit test Framework.

 Approach we will follow is:

1. Write a class which will be having the implementation of the retry functionalities by using a listener for JUnit i.e TestRule .A TestRule is an alteration of how a test method, or set of test methods, is run and reported.
      2.  Then use the implemented feature in your tests by using @Rule which is part of JUnit: Basically Rules allow very flexible addition or redefinition of the behavior of each test method in a test class. Testers can reuse or extend Rules, or can write their own.
Now let us have a look at the code snippet:

package com.junitRetry;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;


public class RetryAnalyzer {

           
             public class Retry implements TestRule {
                    private int retryCount;

                    public Retry(int retryCount) {
                        this.retryCount = retryCount;
                    }

                 
                    public Statement apply(final Statement base, final Description description) {
                        return new Statement() {
                            @Override
                            public void evaluate() throws Throwable {
                                Throwable caughtThrowable = null;

                                //Retry logic goes here
                                for (int i = 0; i < retryCount; i++) {
                                    try {
                                        base.evaluate();
                                        return;
                                    } catch (Throwable ex) {
                                        caughtThrowable = ex;
                                        System.err.println(description.getDisplayName() + ": run iteration number " + (i+1) + " failed");
                                    }
                                }
                                System.err.println(description.getDisplayName() + ": Quiting after " + retryCount + " failures");
                                throw caughtThrowable;
                            }
                        };
                    }
                }

                @Rule
                public Retry retry = new Retry(4);

                @Test
                public void test1() {
                       
                        System.out.println("Test Passed");
                }

                @Test
                public void test2() {
                        System.out.println("FAILED test");
                        Assert.fail();
                }

}



Visit for More Automation Related Discussion:

https://www.youtube.com/channel/UCKSk4gkmO3LXcW17hFUkmcQ/videos






Capturing video of a Running Test In Selenium-Java


Agenda of this blog: To discuss about how to capture the video of a running automation (here Selenium as an example) test-script using Java.

Why it is required:


While coming to running automation test script it is very useful to capture the video of it, because sometimes you have many test scripts (some times more than 1000 test scripts),there its sometimes very tedious to continuously monitor running scripts(which is getting failed) to get the failure reason for the same and merging these video in reports will provide better reporting.
So in that case video recording is very useful as it will show the full execution of the same and from there you can easily identify the place of failure for test-script where and reason for the same.
How to achieve the video recording feature:
We need to follow below approach to achieve the same:

1.  We need to download a jar called monte-screenrecorder and use the same in the project build path .
      2. Write a class which will implement the logic for the recording(Find the below code snippet for the same)and use it in the Test classes.

package recordingVideo;

import static org.monte.media.FormatKeys.EncodingKey;
import static org.monte.media.FormatKeys.FrameRateKey;
import static org.monte.media.FormatKeys.KeyFrameIntervalKey;
import static org.monte.media.FormatKeys.MIME_AVI;
import static org.monte.media.FormatKeys.MediaTypeKey;
import static org.monte.media.FormatKeys.MimeTypeKey;
import static org.monte.media.VideoFormatKeys.CompressorNameKey;
import static org.monte.media.VideoFormatKeys.DepthKey;
import static org.monte.media.VideoFormatKeys.ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE;
import static org.monte.media.VideoFormatKeys.QualityKey;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;

import org.monte.media.Format;
import org.monte.media.FormatKeys.MediaType;
import org.monte.media.math.Rational;
import org.monte.screenrecorder.ScreenRecorder;



public class Record {

                private static ScreenRecorder screenRecorder;
                /**
                 * Method to start the video capturing using monte screen recorder.
                 */
                public static void startVideoCapture()
                {
                                try
                                {
                                                                GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
                                                                int width = gd.getDisplayMode().getWidth();
                                                                int height = gd.getDisplayMode().getHeight();
                                                                java.awt.Rectangle captureArea = new java.awt.Rectangle(width,height);
                                                                GraphicsConfiguration gc = GraphicsEnvironment
                                            .getLocalGraphicsEnvironment()
                                            .getDefaultScreenDevice()
                                            .getDefaultConfiguration();
                                                                File mediaFolder = new File("E:\\tESTvIDEO");     
                                                                screenRecorder = new ScreenRecorder(gc,captureArea,
                                                                       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,mediaFolder);
               
                                                                screenRecorder.start();
                                               
                                }
                               
                                catch(Exception ex){
                                ex.printStackTrace();
                                }
                               
                }             
               




                /**
                 * Method to stop the video recording.
                 */
                public static void stopVideoCapture()
                {
                                try
                                {
                                               
                                                {
                                                                screenRecorder.stop();
                                               
                                                }
                                }
               
                                catch(IOException e)
                                {
                                                e.printStackTrace();
                                }
                                catch (Exception e) {
                                                e.printStackTrace();
                                }
                }
}
  

We need to call to methods, One for starting the recording and other for stopping the recording,we can call these methods in the @BeforeMethod and @AfterMethod(TestNg annotations) respectively.
Find the below code snippet for the Demo test Class which will record the execution of opening chrome browser and navigating to google.com.

package recordingVideo;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class Demo {

                Record record=new Record();
                WebDriver driver;
                @BeforeMethod
                public void startRecording(){
                                System.setProperty("webdriver.chrome.driver", "..\\AdvanceConcepts\\src\\Drivers\\chromedriver.exe");
                                driver=new ChromeDriver();
                                record.startVideoCapture();
                }
               
                @AfterMethod
                public void stopRecording(){
                                record.stopVideoCapture();
                                driver.close();
                }
               
               
                @Test
                public void openGoogleTest(){
                                driver.get("https://www.google.co.in/?gfe_rd=cr&ei=FprqVs3OG-3I8Ae587ioAQ");
                               
                               
                }
}




Visit for More Automation Related Discussion:




https://www.youtube.com/channel/UCKSk4gkmO3LXcW17hFUkmcQ/videos