Thursday, February 27, 2014

Start with TestNG...forget about Junit

Hello Friends

Till now we have seen how a Web-driver code works and some important methods of Web-driver code. Junit has been used since many year and most of the developer still using Junit for code coverage; now we have a strong tool know as TestNG. There are many advantage of TestNG over Junit before we name lets see what is TestNG in short and later we see the small code for it.

What is TestNG
TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing (testing a class in isolation of the others) to integration testing (testing entire systems made of several classes, several packages and even several external frameworks, such as application servers).

Writing a test is typically a three-step process
  • Write the business logic of your test and insert TestNG annotations in your code.
  • Add the information about your test in a testng.xml.
  • Run TestNG.

Advantages of TestNG over Junit
  • In Junit we have to declare @BeforeClass and @AfterClass which is a constraint where as in TestNG there is no constraint like this.
  • Additional Levels of setUp/tearDown level are available in TestNG like @Before/AfterSuite,@Before/AfterTest and @Before/AfterGroup
  • No Need to extend any class in TestNG.
  • There is no method name constraint in TestNG as in Junit. You can give any name to the test methods in TestNG
  • In TestNG we can tell the test that one method is dependent on another method where as in Junit this is not possible. In Junit each test is independent of another test.
  • Grouping of testcases is available in TestNG where as the same is not available in Junit.
  • Also using TestNG your selenium testcase execution can be done in parallel.

Setup
Before moving further i am assuming following things has already been setup


Code
package com.webdriver.testsuite;

import java.util.List;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.shopzilla.webdriver.common.SoftAssert;
import com.shopzilla.webdriver.bizrate.common.Helper;

public class BizrateTestSuite {

Helper helper;
SoftAssert softassert;
WebDriver driver;
String url;

@BeforeClass
public void init(){
helper=new Helper();
                softassert = new SoftAssert();
                helper.getProperties();
driver=helper.getDriver();
}
@AfterClass
public void tearDown(){
driver.close();
}
@Test
public void testLess(){
softassert.flush();
softassert.assertTrue(100<200,"Test Less 1 failed");
softassert.assertTrue(50<200,"Test Less 2 failed");
softassert.assertTrue(90<200,"Test less 3 failed");
softassert.assertAll();
}
@Test
public void testMore(){
softassert.flush();
softassert.assertTrue(10>50,"Test more 1 failed");  // Test should fail
softassert.assertTrue(20>10,"Test more 2 failed");
softassert.assertTrue(30>5,"Test more 3 failed");
softassert.assertAll();
}
        @Test
public void testEqual(){
softassert.flush();
softassert.assertTrue(10==10,"Test eq 1 failed");
softassert.assertTrue(20==20,"Test eq 2 failed");
softassert.assertTrue(30==30,"Test eq 3 failed");
softassert.assertAll();
}

}


Note:
1) To run this code simply right click on code and run as "TestNG Test"
2) Softassert are used so that if some in between test/assert failed then rest test should continue to run and we get one final report after all test finished. Softassert code will provide in later post.

Report

Thursday, October 10, 2013

important methods in webdriver

Hello Friends,

Hope you have now familiar with Web-driver and and how to automate a web page. Now will see some important methods in webdriver.

#implicit wait - it will wait for 10sec
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

#explicit wait
1. Here cond return true
Type 1:
WebElement elem= new WebDriverWait(driver, 10).until(visibilityOfElementLocated(By.id("id_of_web_element")));   

WebElement elem= new WebDriverWait(driver, 10).until(visibilityOfElementLocated(By.className("class_of_element")));

Type 2           
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<WebElement>(){
@Override
    public WebElement apply(WebDriver d) {
    return driver.findElement(By.id( "myDynamicElement" ));
    }});

Type 3
(new WebDriverWait(driverS, 10)).until(new ExpectedCondition<Boolean>() {
             public Boolean apply(WebDriver d) {
            return d.getTitle().toLowerCase().startsWith("Letsbuy");
            }
            });






#By ID
WebElement element=driver.FindElement(By.id(BuyNowButton));


#By Class Name
List<WebElements> buttons=driver.FindElements(By.className("buttons"));


#By Tag Name
WebElement iframe=driver.FindElement(By.tagName("iframe"));


#By Name
WebElement name=driver.FindElement(By.name("firstName")); 

#By LinkText
<a href="www.google.com/selenium.php">open-selenium</a>
WebElement link=driver.FindElement(By.linkText("open-selenium"));

#By Partial Link Text
<a href="www.google.com/selenium_setup.php">open selenium webdriver setup</a>
WebElement link=driver.FindElement(By.partialLinkText("setup"));

#By CSS   [NEED MORE INFO ???]
-->CSS may vary from browser to browser hence not prefered.
-->browser native support for CSS will be used and if brwoser not supporting CSS then "Sizzle" will be used. eg IE 6,7 and FF 3.0 use Sizzle as search engine.

<div id= "food" ><span class= "dairy" >milk</span><span class= "dairy aged" >cheese</span>
WebElement cheese = driver.findElement(By.cssSelector( "#food span.dairy.aged" ));

#By Xpath       
WebElement element = driver.findElements(By.xpath("//div[contains(text(),'Click Payment History')]"))
WebElement element = driver.findElements(By.xpath("//div[@class=\"articleHeader\"])).get(2);

#To get Hidden field
//input[@type="hidden"][@id="FinalPrice"]/@value
//input[@id="FinalPrice"]@value

#Relative XPath:
<table id="serviceInvocations" width="100%" style="display: block; height: 250px; overflow: auto;">
A: ".//*[@id='serviceInvocations']/tbody/tr[3]/td[1]"  


#Xpath Functions:
//div[@id='summaryTip']//div[@class='xpop-content'][text()='You will see a summary of your transfer as you proceed. ']
driver.findElement(By.xpath(".//*[contains(text(),'Sign out')]")).click();



Few More - Xpath:
1. Verify button visibilty [class='select'] get appended if button is enable
String xpBrands = "//ul[@id='views']/li[@class='selected' and position()=1]/div/p/a";

2. Verify count of similar element
String xpTopScrollLinks = "//div[@id='topscrolllinks']/div/a";
int topScrollLinksCount = driver.findElements(By.xpath(xpTopScrollLinks)).size();

//div[@class='promote_favorite']/div[@id='fav_brand_775321 and @class='favorite faved']



Regards
Sheetal :)

start with webdriver

Hello Friends,

Here we are going to learn how to start automating a simple web page using webdriver 2.0.
I am assuming you have installed webdriver and java.

Here we will read a text file which contains n number of links and fetch title of web page.


//code
package com.test.webdriver;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.WebDriver;


public class Titles{
    WebDriver driver;
    private List<String> links = new ArrayList<String>();
      
    public void initialize(){  
        try {
            BufferedReader br = new BufferedReader(new FileReader("href_file.txt"));
            String str = "";
            while ((str = br.readLine()) != null) {
                links.add(str);
            }
            br.close();
        } catch (FileNotFoundException fnf) {
            System.out.println("File Not Found" + fnf);
        } catch (IOException io) {
            System.out.println("IO Exception: " + io);
        }
    }
      
    public void openUrls(){
        try{
            for(String url: links){
//              driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
                driver.get(url);
                System.out.println(driver.getCurrentUrl());        
            }     
        }catch(Exception e){
            e.printStackTrace();
        }
    }
   
    public static void main(String args[]) {
        Titles obj=new Titles();
        driver=new FirefoxDriver();
        obj.initialize();
        obj.openUrls();
    }

}


Please note that "href_file.txt" should present at the same level of your project i.e. above your package, else eclipse will not be able to find file.


Regards
Sheetal