Automation Using Selenium Webdriver

Monday, 10 October 2016

Execute Failed test cases using selenium Real-time Example

Most of the time we have faced this question in interviews that Can we execute only failed test cases in Selenium or can we identify only failed test cases in Selenium and re-run them.



I really love this feature of TestNG that you can run only failed test cases explicitly without any code. This can be easily done by running one simple testng-failed.xml.


                                    Execute Failed test cases using Selenium
                                           Real-time Example


Take an example that you have one test suite of 100 test cases and once you start execution of test suite there  are a number of chances that some test cases will fail.Consider 15 test cases are failing out of 100 now you need to check why these test cases are failing so that you can analyze and find out the reason why they have failed.

Note- Your script can fail due to so many reasons some of them are

1- Some locator has been changed in application because the application is getting new feature- so in this case you need to modify your script in other words you have to refine your script.

You can not avoid maintenance of test script you always have to maintain your scripts
2- Either functionality has been broken- in this case, you have to raise a defect and assign to the respective person.

Execute Failed test cases using Selenium
Steps

1-If your test cases are failing then once all test suite completed then you have to refresh your project . Right click on project > Click on refresh or Select project and press f5.

2-Check test-output folder, at last, you will get testng-failed.xml

3- Now simply run testng-failed.xml.


           

How to run testng-failed.xml
We don’t have to perform any other activity once you will  get testng-failed.xml double click on this and analyze which test case are failing and why . Then modify your script and run it.

To run above xml simple right click on xml then Select run as then TestNG Suite.


or more info visit TestNG official website
Thanks for visiting my blog. Keep visiting.
Please comment below if you finding any issue. Have a nice day ðŸ™‚

How to create dependency between testcases in Selenium




I am sure you must be confused with Title like How to create a dependency between test cases in Selenium but in this post we will see this through example.

In real time, you will come across many situation where you have to create test cases which are dependent on the previous test case.

Take an example I have 3 test case.

First one which verify login credential and start application
Second test case check some validation  or do some activity
Third test case simply just for log-out activity.

If my first test case does not work (failed) that it does not make any sense to run second and third test case so in these type of scenarios you can use dependency between test case.

How can I do this?

TestNG already comes with this features so you can use the same with @Test annotations


Syntax- @Test(dependsOnMethods={"loginTestCase"})

public void testAccount()
{

// sample code

}
Syntax- @Test(dependsOnMethods={"loginTestCase"})

public void testAccount()
{

// sample code

}
How to create dependency between test cases in Selenium



It means this test case name testAccount depends on test case whose name is loginTestCase so until loginTestCase will not execute successfully this test case won’t execute so if loginTestCase will pass this test case will execute and if loginTestCase will fail then this test case won’t execute and runner will skip this test cases and this test case will come under skip test cases.

Let’s implement the same


package Demo;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestMultiple {

@Test
public void testLogin()
{

System.out.println("login done");

}

@Test(dependsOnMethods={"testLogin"})
public void testAccount()
{
System.out.println("Account has been created");

}

@Test(dependsOnMethods={"testLogin","testAccount"})
public void testLogout()
{
System.out.println("logout");

}

}


package Demo;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestMultiple {

@Test
public void testLogin()
{

System.out.println("login done");

}

@Test(dependsOnMethods={"testLogin"})
public void testAccount()
{
System.out.println("Account has been created");

}

@Test(dependsOnMethods={"testLogin","testAccount"})
public void testLogout()
{
System.out.println("logout");

}

}


In the above scenario if testLogin will pass then only testAccount will execute and testLogout will only execute of testLogin and testAccount will  be executed

but if testLogin will fail due to some error or exception the testAccount will not be executed and this test case will skip and testLogout is dependent on testLogin and testAccount so now this will also come into skipped category

Let’s implement again


import org.testng.Assert;
import org.testng.annotations.Test;

public class TestApplication {

@Test
public void testLogin()

{
Assert.assertEquals("Selenium", "Selnium");
System.out.println("login done");

}

@Test(dependsOnMethods={"testLogin"})
public void testAccount()

{
System.out.println("Account has been created");

}

@Test(dependsOnMethods={"testLogin","testAccount"})

public void testLogout()

{
System.out.println("logout");
}
}

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestApplication {

@Test
public void testLogin()

{
Assert.assertEquals("Selenium", "Selnium");
System.out.println("login done");

}

@Test(dependsOnMethods={"testLogin"})
public void testAccount()

{
System.out.println("Account has been created");

}

@Test(dependsOnMethods={"testLogin","testAccount"})

public void testLogout()

{
System.out.println("logout");

}
}


Output

FAILED: testLogin
java.lang.AssertionError: expected [Selnium] but found [Selenium]
at org.testng.Assert.fail(Assert.java:94)
SKIPPED: testAccount
SKIPPED: testLogout

===============================================
Default test
Tests run: 3, Failures: 1, Skips: 2
===============================================

===============================================
Default suite
Total tests run: 3, Failures: 1, Skips: 2
===============================================

OUTPUT in HTML

Saturday, 8 October 2016

Advanced-Selenium-Autoamtion-Real-Time-Support PPT

EMIDS Technologies Last Week Asked 2 Years Selenium Testing Position

EMIDS  INTERVIEW QSNFOR 2 YEARS SELENIUM TESTING POSITION.

      Prepare  Code Also Some Scenarios Asked 

1ST round-TECHNICAL
·         Introduce yourself  tell something about your last project.
·         Which framework  you have used and why?
·         Why automation ?
·         Write the format of XML file for BATCH EXICUTION?
·         How synchronisation resolved in automation?
·         How many wait statements you know ?
·         What  is polymorphisim?
·         Have u used constructor in WebDriver?

2nd round – TECHNICAL

·         Tell me about your project and responsibilities?
·         Which module u worked on ur project ?
·         Tell me the flow of your framework?
·         Write a  java code to read the data through excel file?
·         I have some reusable methods and i have some new feture,so i want to acess the reusable methods to my current application,how can i do that?
·         Is it possible to write the xpath using IE browser?
·         What exactly your file structure looks like when you are automating something by using of eclipse ?
·         How did you verify that given number on webpage in sorted order ?
·         How can i do priority based testing using webDriver ?
·         Write a login  code using page factory ?
·         Is that necessary to creat Generic Lib. For  every project?
·         Write a code for screen shot ?
·         Have u ever faced like You don’t have requirement document  and  You have to test,how wil you do that?
·         Why we r using some tool for reporting?
·         What is TestNg ?tell me the annotations of TestNG? (if you are using TestNG)
·         Can you write a sample  for parallel execution  in TestNG.xml file?
·         How are you maintaining the objects in your project?
·         What is constructor ? what is super ()?
·         What is Encapsulation?
·         What is the difference between interface and abstract class?
·         What is poly morphism?
·         Actually  X-path writing a confusion task for me, is there any way to find webElement in UI?
·         How wil you capture the dynamic object using selenium webDrive?
·         Tell me the syntax for Implicity wait() and Explicity wait()

3RD round-maneger
Gv ur intro with your roles and responsibilities?
How many bug you hv found on your project?
Can you please explain flow of your project?













Friday, 7 October 2016

How to capture screenshot for failed test cases in Selenium Webdriver

How to capture screenshot for failed test cases in Selenium Webdriver

Writing Selenium Webdriver script is not enough everyone can design script nowadays. We need to design script in such a way that we can utilize script code as much as possible.This article will talk about Capture screenshot in selenium for failed test cases.
I am a big fan of screenshots in Automation because it helps me a lot to identify the exact issue.

Generally, scripts fail in 2 situations.

1-If script has some issue (some locator has been changed or application has some changes)- In this case, we need to maintain our Selenium script.
2-Due to application issue- In this case, we need to inform to respective point of contact (Manual Tester or Developer)

How to Capture screenshot in selenium for failed test cases

Previously I have covered a post on capture screenshot in Selenium so if you have not gone through the previos post then I will highly recommend you to please go through the post and youtube as well.

Today we will see something different How to capture a screenshot for failed test cases in Selenium Webdriver.
Here I will be using two new topics which will help us to achieve the same.
1-We will use ITestResult Interface which will provide us the test case execution status and test case name.
Please refer official doc for ITestResult
2- @AfterMethod is another annotation of TestNG which will execute after every test execution whether test case pass or fail @AfterMethod will always execute.
Please refer official doc for @AfterMethod
If you are new to TestNG and want to explore more on TestNG then I will recommend you to please go through below TestNG topics.
I have covered a couple of topics for TestNG. You can check all TestNG Tutorial here
Now let’s get started and will see through a complete program
// Create a package in eclipse
package captureScreenshot;

// Import all classes and interface
import java.io.File;
import library.Utility;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
public class FacebookScreenshot {
// Create Webdriver reference
WebDriver driver;
@Test
public void captureScreenshot() throws Exception
{
// Initiate Firefox browser
driver=new FirefoxDriver();
// Maximize the browser
driver.manage().window().maximize();
// Pass application url
driver.get("http://www.facebook.com");
// Here we are forcefully passing wrong id so that it will fail our testcase
driver.findElement(By.xpath(".//*[@id='emailasdasdas']")).sendKeys("jaganthota");
}
// It will execute after every test execution 
@AfterMethod
public void tearDown(ITestResult result)
{
// Here will compare if test is failing then only it will enter into if condition
if(ITestResult.FAILURE==result.getStatus())
{
try 
{
// Create refernce of TakesScreenshot
TakesScreenshot ts=(TakesScreenshot)driver;
// Call method to capture screenshot
File source=ts.getScreenshotAs(OutputType.FILE);
// Copy files to specific location here it will save all screenshot in our project home directory and
// result.getName() will return name of test case so that screenshot name will be same
FileUtils.copyFile(source, new File("./Screenshots/"+result.getName()+".png"));
System.out.println("Screenshot taken");
catch (Exception e)
{ 
System.out.println("Exception while taking screenshot "+e.getMessage());
}
// close application
driver.quit();
}
}
Above code will execute fine and if test case will fail it will capture the screenshot. Check below screenshot
                                       

Above code is fine but still we need to enhance our code so that we can reuse.

We will create Utility class which will have one method which will capture the screenshot.
Code to create method for screenshot
package library;
import java.io.File;import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class Utility 
{
public static void captureScreenshot(WebDriver driver,String screenshotName)
{
try 
{
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("./Screenshots/"+screenshotName+".png"));
System.out.println("Screenshot taken");
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
}


Thursday, 6 October 2016

How to Create Object Repository in Selenium Webdriver- Selenium

Whenever you talk about repository by the name itself you can think thatit is kind of storage. Object repository is the collection of object and object here is locator.Object Repository in Selenium Webdriver is quite easy todesign so let’s get started.

Here locator means web element id, name, CSS, XPath, class name etc.

Object Repository in Selenium Webdriver

To understand an importance of Object repository, we will take real time scenario.

The scenario is you have 100 test cases and in all test cases, you have login scenario. If your application changes now and some locator changes like id changes from email to login email then you have to modify all the test cases and you have to change the id.

This process does not make any sense so to overcome with this we will move all locator in a separate file and we will link all test cases to this file.
In case any changes happen in our locator we will simply change in that file, not our test cases.

This will increase the modularity of test cases and I will strongly suggest thatyou should use Object Repository in Automation.

Object Repository in Selenium Webdriver- Selenium Tutorial Precondition

1- Project should be created and Selenium jars should be added- Click here to configure .

2- Now create a new file and give file name as Object_Repo (depends on you)with extension .
properties

For this right click on project > create a new file > Specify name




Select folder and specify name & extension


3- Now file is created > Double click on file > File will open in Edit mode
Object repository works on KEY and Value pair so we will specify Keys based on our project and in values we will give locator value.
In below example, I have taken xpath for username,password and loginbutton for facebook loginpage.
Key you can write based on your project standard, but value should be correct which is coming from application
<span style="font-size: 14pt; font-family: arial, helvetica, sans-serif;">
facebook.login.username.xpath=.//*[@id='email']
facebook.login.password.xpath=.//*[@id='pass']
facebook.login.Signup.xpath=.//*[@id='loginbutton']</span>



4- Write Selenium script and use the same in script

Object Repository in Selenium Webdriver- Selenium Tutorial

package ObjectRepoExample;
<span style="font-size: 14pt; font-family: arial, helvetica, sans-serif;">import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class TestFacebook {
@Test
public void TestOR() throws IOException{
// Specify the file location I used . operation here because
//we have object repository inside project directory only
File src=new File(".Object_Repo.properties");
// Create  FileInputStream object
FileInputStream fis=new FileInputStream(src);
// Create Properties class object to read properties file
Properties pro=new Properties();
// Load file so we can use into our script
pro.load(fis);
System.out.println("Property class loaded");
// Open FirefoxBrowser
WebDriver driver=new FirefoxDriver();
// Maximize window
driver.manage().window().maximize();
// Pass application
driver.get("http://www.facebook.com");
// Enter username here I used keys which is specified in Object repository.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.username.xpath"))).
sendKeys("Selenium@gmail.com");
// Enter password here I used keys which is specified in Object repository.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.password.xpath"))).
sendKeys("adsadasdas");
 / Click on login button here I used keys which is specified in Object repository.
// Here getProperty is method which
// will accept key and will return value for the same
driver.findElement(By.xpath(pro.getProperty("facebook.login.Signup.xpath"))).click(); 
}}
</span>