Selenium Crash Course

 

What is selenium?

Selenium is an open-source framework to automate and perform software testing such as smoke tests, integration tests, etc. on web applications. It provides a playback/recording tool and domain-specific language.

Get started with Selenium:

  • Driver Initialization Basics:

    • Firefox WebDriver driver = new FirefoxDriver();
    • Chrome WebDriver driver = new ChromeDriver();                 
    • Internet Explorer WebDriver driver = new SafariDriver();
    • Safari Driver WebDriver driver = new InternetExplorerDriver();
  • Driver Initialization Advanced:

A. Load firefox from a different location:

System.setProperty(“webdriver.firfox.bin”,“path/to/firfox/binary”);
FirefoxProfilefp= new FirefoxProfile();

B. Load firefox addons

File file=new File(“path/to/extension.xpi”);
fp.addextension(file)

Selenium Locators:

Selenium locators are used to finding and match the webpage elements that selenium interacts with. Following are some locators in selenium:

  • Locating by ID
driver.findElement(By.id("q")).sendKeys("Se lenium 3");
  • Locating by Name
driver.findElement(By.name("q")).sendKeys ("Selenium 3");
  • Locating by Xpath
driver.findElement(By.xpath("//input[@id='q'])).sendKeys("Selenium 3");
  • Locating Hyperlinksby Link Text
driver.FindElement(By.LinkText("edit this page")).Click();
  • Locating by DOM
dom =document.getElementById('signinForm')
  • Locating by CSS
driver.FindElement(By.CssSelector("#rightbar> .menu >li:nth-of-type(2) > h4"));
  • Locating by ClassName
driver.findElement(By.className("profileheader"));
  • Locating by TagName
driver.findElement(By.tagName("select")).C lick();
  • Locating by LinkText
driver.findElement(By.linkText("NextP age")).click();
  • Locating by PartialLinkText
driver.findElement(By.partialLinkText(" NextP")).click();

Selenium Navigators:

The navigator interface in selenium helps in moving backward and forwards in the browser’s history. Following are some navigator commands you can use:

  • Navigate to URL
driver.get(“http://newexample.com”)
driver.navigate().to(“http://newexample.com”)
  • Refresh page
driver.navigate().refresh()
  • Navigate forwards in browser history
driver.navigate().forward()
  • Navigate backward in browser history
driver.navigate().back()

TestNG:

TestNG is an open-source framework for automated testing. The NG in TestNG stands for Next Generation. It is similar to Junit but with more functionality to offer. Following are the TestNG annotations:

  • @test: This annotation marks a class or method as a part of a test
  • @BeforeSuite: This annotation makes sure that the method only run once before all the tests have run
  • @AfterSuite: This annotation makes sure that the method runs once after the execution of all the tests
  • @BeforeTest: This annotation will make sure that the method marked with this annotation runs before the first method annotated with @test
  • @AfterTest: This annotation will make sure that the method marked with this annotation runs after all the methods annotated with @test execute all the classes inside <test> tag in the testng.xml file.
  • @BeforeGroups : A method annotated with this annotation will run before all the first test methods run in that specific group
  • @AfterGroups: A method annotated with this annotation will run after all the test methods run in that specific group
  • @BeforeClass: A method annotated with this annotation will run only once per class and before all the first test methods run
  • @AfterClass: A method annotated with this annotation will run only once per class and after all the test methods run
  • @BeforeMethod: A method annotated with this annotation will run before every @test annotated method
  • @AfterMethod: A method annotated with this annotation will run after every @test annotated method

JUNIT

JUNIT (Java Unit Testing Tool) is a framework used to perform unit-level testing. Following are the JUNIT annotations:

  • @Test: test method to run with public void return type
  • @After: method to run after the test method
  • @AfterClass: method to run before the test method
  • @Before: method to run before the test method
  • @BeforeClass: method to run once before any of the test methods in the class have been executed
  • @Ignore: This annotation is used to ignore a method

Windows:

Sometimes the web applications may have multiple frames or windows. Selenium assigns each window a unique alphanumeric id which is called window handle. Selenium then uses the id to switch control among windows.

String handle=driver.getWindowHandle();
Set<String> handles = getWindowHandles();
driver.switchTo().window(handle);
  • How to switch to a newly created window

 String curWindow=driver.getWindowHandle();
  • Get all window handles
Set<String> handles = getWindowHandles();
For(string handle: handles){
If (!handle.equals(curWindow))
{driver.switchTo().window(handle);
}
}

Frames

  • Using Frame Index:
driver.switchTO().frame(1);
  • Using Name of Frame:
driver.switchTo().frame(“name”)
  • Using web Element Object:
driver.switchTO().frame(element);
  • Get back to main document:
driver.switchTO().defaultContent();

Operations:

In selenium there are certain operations that can be performed on the web elements. Following is the list of those operations along with their respective syntax:

  • Launch Webpage:
get("www.webdriverinselenium.com");
  • Click Button: 
findElement(By.id("submit")).click();
  • Handle Alert:
AlertAlertpopup = driver.switchTo().alert();
  • Disable a Field:
getElementsByName('') [0].setAttribute('disabled', '')
  • Enable a Field :
getElementsByName('') [0].removeAttribute('disabled');
  • Screenshot : 
File snapshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(snapshot, new File("C:\\screenshot.jpg"));
  • Print the Title of the Page:
String pagetitle = driver.getTitle();
System.out.print(pagetitle);
  • Implicit Wait: 
manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  • Explicit Wait:
WebDriverWait wait = new WebDriverWait(driver, 20);
  • Sleep :
Thread.Sleep(10);

Alerts:

Sometimes a message box pops up on the screen to display some kind of notification to the user or maybe an ask for permission or to display a warning etc. These messages are called alerts. Alert interface provides some ways to handle the alerts in selenium:

Capture the alert message:

driver.switchTO().alert.getText();

Click on the ‘OK’ button of the alert:

driver.switchTO().alert.accept();

Click on the ‘Cancel’ button of the alert:

driver.switchTO().alert.dismiss();

Send some data to the alert box:

driver.switchTO().alert.sendKeys(“Text”);

Selenium Grid:

Selenium Grid helps selenium run multiple tests across different operating systems, browsers, and machines in parallel.

  • Start hub:
java-jar selenium-server- standalone-x.xx.x.jar-role hub
  • Start node:
java-jar selenium-server- standalone-x.xx.x.jar-role node-hub
http://localhost:4444/grid/register
  • Server:
http://localhost:4444/grid/console

Mithun Kumar

I am Mithun Kumar, a freelance and working software professional. I have around 6 years of experience in software Quality Assurance in Manual and Automation with Various tools and Technology. I am always learning new technologies and find myself up to date with the latest software technologies.

Post a Comment

Thanks! for you valuable comment.

Previous Post Next Post