Saturday, November 30, 2013

Selenium webdriver Interview Questions & Anwser

Q 1. Can we create multiple instances with selenium web driver with same Browser?

Ans: Yes, We can Create multiple Instances with selenium web driver.

ex: package Sample Package;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Class1
 {
public static void main(String[] args) throws InterruptedException
{
//Create 1st instance for IE
System.setProperty("webdriver.ie.driver", "C:\\Selenium Automation\\IEDriverServer.exe");
InternetExplorerDriver ds1 = new InternetExplorerDriver();
ds1.get("http://google.co.in");
Thread.sleep(3000);
ds1.findElement(By.name("q")).sendKeys("software testing");
Thread.sleep(3000);
ds1.findElement(By.name("btnK")).click();
//Create 2nd instance for IE
System.setProperty("webdriver.ie.driver", "C:\\Selenium Automation\\IEDriverServer.exe");
InternetExplorerDriver ds2 = new InternetExplorerDriver();
ds2.get("http://www.flipkart.com/");
Thread.sleep(3000);
ds2.findElement(By.name("q")).sendKeys("Computers");
Thread.sleep(3000);
//Create 3rd instance for IE
System.setProperty("webdriver.ie.driver", "C:\\Selenium Automation\\IEDriverServer.exe");
InternetExplorerDriver ds3 = new InternetExplorerDriver();
ds3.get("http://google.co.in");
Thread.sleep(3000);
ds3.findElement(By.name("q")).sendKeys("software testing");
Thread.sleep(3000);

Note: Create number of instances but once we run the program it will finish the 1st instance and 2nd instance then 3rd instance . it will not open multiple browsers at a time

Q2. How can we run my application on to different browesrs ?

Ans: By Creating different instances with different browser.

package SamplePackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import BackUpprograms.webdriver_Reg;

public class Class1 {

public static void main(String[] args) throws InterruptedException
{
// Create an Instance for IE browser
System.setProperty("webdriver.ie.driver", "C:\\Selenium Automation\\IEDriverServer.exe");
InternetExplorerDriver ds1 = new InternetExplorerDriver();
ds1.get("http://google.co.in");
Thread.sleep(3000);
ds1.findElement(By.name("q")).sendKeys("software testing");
Thread.sleep(3000);
ds1.findElement(By.name("btnK")).click();

// Create an Instance for Firefox browser
WebDriver ds = new FirefoxDriver();
ds.get("http://google.co.in");
Thread.sleep(3000);
ds.findElement(By.name("q")).sendKeys("software testing");

}
}



Thursday, November 28, 2013

TestNG Annotations

Summary of TestNG Annotations

@BeforeSuite: The annotated method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class have been run.
@BeforeMethod: The annotated method will be run before each test method.
@AfterMethod: The annotated method will be run after each test method.
@Test: The annotated method is a part of a test case

Read more at http://www.guru99.com/all-about-testng-and-selenium.html#YiERkXhmJc0DBTd4.99

Selenium Frame Work Structure



Automated Selenium Testing framework using TestNG and Selenium-RC
·          Introdution
This framework is developed using ANT, TestNG, JUnit and Selenium. Using this framework, a user is able to create an automated test case, which can be run later by executing a single command. This framework uses different frameworks are as follows:
Selenium: This framework is needed for recording a testcase, exporting it into Java, and executing it on a browser
TestNG: This framework is used to organize different tests, and to report results.
ANT: provides the glue to hold everything together, and execute basic commands.
JUnit: This framework is used only for reports i.e JUnit Reports.

·          About the Framework architecture and struture: 
This framework has one testsuite called ApplicationTestsuite and thisi is java class which extends BaseSeleneseTestsuite that in turn extends SeleneseTestCase that does the required setup and teardown.
· ApplicationTestsuite .java: This test logs into the your application console using the username/password. It has only methods and each method is one testcase.
. BaseSeleneseTestsuit.java: This class has two methods setup() and tearDown(). Setup() method is used for setting up the environment meaning creating selenium instance and launching the browser to test and other method is tear down which is mainly for stopping the selenium and killing the browser.
The folder structure or contents of SeleniumTestFramework.zip of this framework is as follows:
|----------SeleniumTestFramework
|-------config
|-------lib
|-------test-src
|-------build.xml
|-------config.properties
|-------test-output
|-------build
· The config directory contains testng.xml file, and is a place holder for configuration files.
· The lib directory contains required jar files, and is a place holder for other library jars/zips.
· The test directory contains test java files and is a place holder for other test files. 
Once the tests are run, build and
 test-output directories will be created.
· The config.properties is properties file.
· The build.xml file is taking care of starting selenium server, compiling testcases and running the testsuite.
· The build directory contains compiled classes, and is a volatile directory that is deleted by the target clean in build.xml file.

. The test-output directory contains result files, and is generated by TestNG.

·          How to write a test case:
Record a testcase using Selenium IDE (Firefox browser only), Export the test case into Java as mentioned below steps.
· Open the website you’d like to test in Firefox browser
· Start the selenium IDE from your Firefox browser:Tools ->Selenium IDE
· Ensure that the Base URL in Firefox is the same as the website you want to test
· Start clicking on the website. Selenium will record your actions.
· When finished, do: File -> Export Test As. -> Java – Selenium RC and save the java file.
The saved java will have one mehod called testNew(), this method will be the one test case. 
·          How to add a test case to framework:
You can create a new java file (Testsuite) and add the testcase to new file or you can add the test case to existing the java file (Testsuite).
  1. Follow the below mentioned steps to add the test case to the existing framework or testsuite.
· Copy the testNew() method to existing testsuite(java file) i.e either ApplicationTestsuite.java based on the category.
· Rename the testNew() method to appropriate or meaningful name.
· Add the method level Annotation to the method (testcase) using TestNG. Annotations are mainy used for adding the testcase to a particular group and sequence to run the testcase.
  1. Follow the below mentioned steps to add the test case to new Testsuite (Java file)of the framework.
    • Write new Java file called NewTestsuite.javaand extend the BaseSeleneseTestsuiteclass.
    • Add the generated testNew() method to existing testsuite(java file) toNewTestsuite.java
    • Rename the testNew() method to appropriate or meaningful name.
    • Add the method level Annotation to the method (testcase) using TestNG.
    • Annotations are many used for adding the test case to a particular group and sequence to run the testcase.
    • Make a entry of this new testsuite (NewTestsuite) to config/testing.xml.
·          How to run the automated test suite: 
Follow the below steps to run the Automated test suite
  • Edit the “config.properties” file to mention application URL, browser type and application user name and password.
  • Open the command prompt and go to extracted directory, e.g.: c:/ SeleniumTestFramework
  • Set JAVA_HOME and ANT_HOME
  • Execute the command: “ant” from ‘SeleniumTestFramework’.
  • You should see the Selenium server window and new browser window open up, and run through your test suit.

· Reports: 
This framework generates both Junit and TestNG Reports. Check reports generated by TestNG and JUnit under ‘SeleniumTestFramework/test-output’ directory. Open the SeleniumTestFramework/test-output /index.html to see the TestNG reports and Open the SeleniumTestFramework/test-output / junit-noframes.html to see the JUnitreports.
Download the required SeleniumTestFramework.zip file from here or
Download the selenium-rc from here and testng from here
  • BaseSeleneseTestsuite.java

Please find the Java files and the build.xml which is required for this framework. I couldn't upload the file

package com.example.selenese.tests;

import java.util.Properties;
import java.io.File;
import java.io.FileInputStream;

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import java.util.regex.Pattern;

@Test(sequential = true)
public class BaseSeleneseTestsuite extends SeleneseTestCase {

public static Selenium selenium;
public static String TIMEOUT_PERIOD ="60000";

public static String APP_USER_NAME;
public static String APP_USER_PASSWD;
public static String strPath;

public String APP_URL;
public String BROWSER_TYPE;

@BeforeSuite(alwaysRun = true)
public void setUp() {
try{
//strPath = System.getProperty("user.dir");
Properties properties = new Properties();
properties.load(new FileInputStream(new File("config.properties")));

APP_USER_NAME = properties.getProperty("APP_USER_NAME").trim();
APP_USER_PASSWD = properties.getProperty("APP_USER_PASSWD").trim();
APP_URL = properties.getProperty("APP_URL").trim();
BROWSER_TYPE = properties.getProperty("BROWSER_TYPE").trim();

System.out.println("The APP_USER_NAME is : "+APP_USER_NAME);
System.out.println("The APP_USER_PASSWD is : "+APP_USER_PASSWD);
System.out.println("The APP_URL is : "+APP_URL);
System.out.println("The BROWSER_TYPE is : "+BROWSER_TYPE);
BROWSER_TYPE="*"+BROWSER_TYPE;

}catch(Exception e){
e.printStackTrace();
}
selenium = new DefaultSelenium("localhost", 4444, BROWSER_TYPE, APP_URL);
selenium.start();
selenium.setSpeed("500");
selenium.setTimeout(TIMEOUT_PERIOD);
selenium.windowMaximize();
}

@AfterSuite(alwaysRun = true)
public void tearDown() {
try {
checkForVerificationErrors();
} finally {
selenium.stop();
}
}
  • ApplicationTestsuite.java 

package com.example.selenese.tests;

import java.util.Properties;
import java.io.File;
import java.io.FileInputStream;

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import java.util.regex.Pattern;

@Test(sequential = true)
public class ApplicationTestsuite extends BaseSeleneseTestsuite {
@Test(groups = {"initGoup"})
public void testAppLogin() throws Exception {
try {
selenium.open("/ccore/Login.jsp");
selenium.type("j_username", APP_USER_NAME);
selenium.type("j_password", APP_USER_PASSWD);
selenium.click("button1");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
checkForVerificationErrors();
}
finally {
clearVerificationErrors();
}
}

@AfterClass(alwaysRun = true)
public void testAppLogout() throws Exception {
try {
selenium.selectFrame("relative=up");
selenium.selectFrame("top");
selenium.click("//font");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
checkForVerificationErrors();
}
finally {
clearVerificationErrors();
}
}

@Test(dependsOnMethods="testAppLogin",groups = { "initGoup" })
public void testAddGateway() throws Exception {
try {
selenium.selectFrame("relative=up");
selenium.selectFrame("body");
selenium.click("//input[@value='Add New Component']");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.type("name", "testGateway");
selenium.type("url", "http://localhost:9700/gateway");
selenium.click("button1");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.click("//input[@value=' Ok ']");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
checkForVerificationErrors();
}
finally {
clearVerificationErrors();
}
}

@Test(alwaysRun=true,dependsOnMethods="testAddGateway",groups = { "initGoup" })
public void testRegisterService() throws Exception {
try {
selenium.selectFrame("relative=up");
selenium.selectFrame("menu");
selenium.click("link=Policy Management");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.click("link=Register Services");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.selectFrame("relative=up");
selenium.selectFrame("body");
selenium.click("link=Services");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.click("//input[@name='Submit' and @value='Add New Service']");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.type("serviceName", "CRSrv");
selenium.type("serviceVersion", "1.0");
selenium.type("wsdlUrl", "http://localhost:9700/orabpel/default/CreditRatingService/1.0/CreditRatingService?wsdl");
selenium.click("submit");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.click("//input[@value='Finish']");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.click("//input[@value=' Ok ']");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.click("link=commit");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.click("//input[@value=' Ok ']");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
checkForVerificationErrors();
}
finally {
clearVerificationErrors();
}
}

@Test(alwaysRun=true,dependsOnMethods="testRegisterService",dependsOnGroups = { "initGoup" },groups = {"nextGroup"})
public void testGatewayCheck() throws Exception {
try {
selenium.selectFrame("relative=up");
selenium.selectFrame("menu");
selenium.click("link=Tools");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.click("link=Test Page");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.selectFrame("relative=up");
selenium.selectFrame("body");
selenium.type("wsdl", "http://localhost:9700/gateway/services/SID0003001?wsdl");
selenium.click("wsdlURL");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
selenium.type("ora_testpage_process_part_payload", "12345");
selenium.click("invoke");
selenium.waitForPageToLoad(TIMEOUT_PERIOD);
checkForVerificationErrors();
}
finally {
clearVerificationErrors();
}
}
  • build.xml








property="test.classpath"
refid="classpath_jars"/>

classname="org.testng.TestNGAntTask" />

debug="true"
destdir="${test.build.dir}"
includes="*.java"
srcdir="${test.src}"
target="1.5"
classpath="${test.classpath}"
>
ant will execute the full test suite

src="http://localhost:4444/selenium-server/driver/?cmd=shutDown"
dest="result.txt" ignoreerrors="true" />

testing.xml


config.properties

#BROWSER_TYPE= iexplore
#BROWSER_TYPE= chrome
#BROWSER_TYPE= firefox


APP_URL = http://localhost:8080/
APP_USER_NAME = weblogic
APP_USER_PASSWD = weblogic
BROWSER_TYPE= chrome



Selenium Interview Questions -- 3

Selenium Page Object Elements



I developed my selenium testing after looking into your page object designed pattern training. It was really helpful. Thanks for posting it 

I have written Page object class for Login page to test UI look & feel for web, iphone & tablet. For each verification I have written a method to return cssValue or text for that element.   

Writing that increases lot method defined in a single class. Is there any way to reduce no of methods declared in a page object class? 

Example: 

    public String getBannerCssValue(String cssValue){ 
        return getCssValue(driver.findElement(banner), cssValue); 
    } 

    public String getSmartPhoneLegendText(){ 
        return getElementText(driver.findElement(smartPhoneLegend)); 
    } 

    public String getSmartPhoneLegendCssValue(String cssValue){ 
        return getCssValue(driver.findElement(smartPhoneLegend), cssValue); 
    } 

    public String getTabletLegendText(){ 
        return getElementText(driver.findElement(tabletLegend)); 
    } 

    public String getTabletLegendCssValue(String cssValue){ 
        return getCssValue(driver.findElement(tabletLegend), cssValue); 
    } 

    public String getButtonTextValue(){ 
        return getAttribute(driver.findElement(login), "value"); 
    } 

    public String getSubmitButtonCssValue(String cssValue){ 
        return getCssValue(driver.findElement(login), cssValue); 
    } 

    public String getForgotPasswordCssValue(String cssValue){ 
        return getCssValue(driver.findElement(forgotYourPassword), cssValue); 
    } 

    public String getTabButtonTextValue(){ 
        return getAttribute(driver.findElement(tabletSubmit), "value"); 
    }





You can have your page objects extend the above generic SystemTestPage class.


package com.systemtest.page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import fsg.wrap.systemtest.SystemTestPage;
public class LoginPage extends SystemTestPage {
        
    @FindBy(name = "username")
    @CacheLookup
    private WebElement userNameInput;
  
 @FindBy(name = "password")
    @CacheLookup
    private WebElement passwordInput;
    @FindBy(xpath ="//input[@type=\"submit\"]")
    @CacheLookup
    private WebElement submitButton;
     
    public LoginPage(WebDriver driver){
        super(driver);
    }
     
    public void login(String userName, String password) {
        userNameInput.sendKeys(userName);
  userNameInput.sendKeys(password);
        submitButton.submit();
    }
     
    public String getUserName(String userName) {
        WebElement element = driver.findElement(By.xpath("//td[text()=" + userName + "]"));
        return element.getText();
    }
}


Write the JUnit class using the page objects defined above and assert the results. These JUnit test cases can be run to test your web pages.


package com.unittests;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.systemtest.page.LoginPage;
public class LoginTest {
     
    private static final String BASE_URL = "http://localhost:7001/login/login.htm";
    private static final String USER_NAME = "John";
 private static final String PASSWORD = "aa44"
     
    private WebDriver driver;
    private WebDriverWait wait;
    private LoginPage loginPage; // the page object
     
    @Before
    public void setUp() {
        driver = new FirefoxDriver();
        wait = new WebDriverWait(driver, 5);
        driver.get(BASE_URL);
        loginPage = PageFactory.initElements(driver, LoginPage.class);
    }
     
    @Test
    public void testLogin() throws Exception {
        loginPage.login(USER_NAME, PASSWORD);
        Assert.assertEquals(MAC, loginPage.getUserName(USER_NAME));
    }
    @After
    public void tearDown() {
        driver.quit();
    }

}

Q. What are selenium locators? What tools do you use to locate them?
A. Selenium Locators are the way of finding the HTML element on the page to perform a Selenium action on. The example above has a line asshown below to extract the username element from the Login response page. This uses an XPath expression to locate the element.

?
1
2
3
4
public String getUserName(String userName) {
    WebElement element = driver.findElement(By.xpath("//td[text()=" + userName + "]"));
    return element.getText();
}

The XPath expression will be something like //td[[text()=John] which looks for a td element with text value "John".

The annotation in the above example is also a locator by name as shown below

?
1
2
3
@FindBy(name = "username")
@CacheLookup
private WebElement userNameInput;  

This will match the HTML snippet

?
1
<input type="text" name="username">

You could also find by tagName, id, css, etc.


There are handy tools to identify the HTML elements or locators.

  • Selenium IDE, which is a Firefox plugin useful in identifying the locators, debugging, etc.


Q. In your experience, what are some of the challenges with Selenium?
A. In general, badly written test cases whether junit tests or web tests, the biggest complaint is about writing test cases that are not maintainable. Unmaintainable automated test cases can take more time than manual tests. So, it is important to write quality test cases by clearly separting the page objects from the test cases as demonstrated  in the Q&A above. The use of the locators need to be carefully thought through. For example, some frameworks like JSF dynamically generate HTML element IDs. So, if IDs are used in your tests, then the test cases may fail if the IDs have changed. The solution to this problem is to use XPath to find the relevant HTML elements. The ClickAndWait action will not work for AJAX calls, and use "waitForElement" instead. 

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...