Thursday, June 19, 2014

First Test case with TestNG

Steps to follow: 
  1. Press Ctrl+N , select “TestNG Class” under TestNG category and click Next. Or Right click on Test Case folder, go to TestNG and select “TestNG Class“. 
  2. If your project is set up and you have selected the Test Case folder before creating TestNG class then the source folder and the package name will be prepopulated on the form. Set class name as ‘TestNG‘. Under Annotations, check “@BeforeMethod”, “@AfterMethod” and click Finish. That’s it.
  3. Now it will display the newly created TestNg class under the Test Case package (folder). TestNG class will be displayed with three empty methods. One method f() by default and before & after method, as selected during the creation of the class. Now it is the time to write the first TestNG test case. 
  4. Let’s take an example of login and divide the test case in to three parts.   
@BeforeMethod : Launch Firefox and direct it to the Base URL   
@Test : Enter Username & Password to Login, Print console message and Log out  
@AfterMethod : Close Firefox browser


package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;

public class TestNG {
            public WebDriver driver;
@BeforeMethod
  public void beforeMethod() {
      // Create a new instance of the Firefox driver
      driver = new FirefoxDriver();
      //Put an Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      //Launch the Website
      driver.get("http://www.gmail.com");
  }

  @Test
  public void testLogin() {
      // Find the element that's ID attribute is 'txtUsername' (Username)
      // Enter Username on the element found by above desc.
      driver.findElement(By.id("txtUsername")).sendKeys("testuser1");
      // Find the element that's ID attribute is 'txtPwd' (Password)
      // Enter Password on the element found by the above desc.
      driver.findElement(By.id("txtPwd")).sendKeys("Test@123");
      // Now submit the form.
      driver.findElement(By.id("btnLogin")).click();
      // Print a Log In message to the screen
      System.out.println(" Login Successfully, now it is the time to Log Off buddy.");
      // Find the element that's ID attribute is 'btnLogout'
      driver.findElement(By.id("btnLogout")).click();
  }

 @AfterMethod
  public void afterMethod() {
              // Close the driver
      driver.quit();
  }
} 
5. Run the test by right click on the test case script and select Run As > TestNG Test. 
Results of running the Testng Test Case
6. Give it few minutes to complete the execution; once it is finished the results will be displayed in the TestNg Result window.
       
        
It displayed ‘passed : 1′. This means test is successful and Passed.
There are 3 sub tabs. “All Tests”, “Failed Tests” and “Summary”. Just click “All Tests” to see what is there.
 

7. TestNG also produce HTML reports. To access those reports go to the Project directory and open test-output folder. 
8. Open ‘emailable-report.html‘, as this is an html report open it with browser.
9. TestNG also produce ‘index.html‘ report and it resides in the same test-output folder. This report gives the link to all the different component of the TestNG reports like Groups & Reporter Output. On clicking these will display detailed descriptions of execution.

Install TestNG in Eclipse

It is easy to install TestNG, as it comes as a plugin for Eclipse IDE. Prerequisite for installing TestNG is your Internet connection should be up & running during installation of this plugin and Eclipse IDE should be installed in your computer.
Steps to follow:
  1. Launch the Eclipse IDE and from Help menu, click “Install New Software”. 
  2. You will see a dialog window, click “Add” button. 
  3. Type name as you wish, let’s take “TestNG” and type “http://beust.com/eclipse/” as location. Click OK. 
  4. You come back to the previous window but this time you must see TestNG option in the available software list. Just Click TestNG and press “Next” button. 
  5. Click “I accept the terms of the license agreement” then click Finish. 
  6. You may or may not encounter a Security warning, if in case you do just click OK. 
  7. Click Next again on the succeeding dialog box until it prompts you to Restart the Eclipse.
  8. You are all done now, just Click Yes. 
  9.  Proceed with your workplace.
  10. After restart, verify if TestNG was successfully installed. Right click on your project and see if TestNG is displayed in the opened menu.

TestNG Introduction



TestNG Introduction
TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionality that make it more powerful and easier to use.
TestNG is an open source automated testing framework; where NG of TestNG means Next Generation. TestNG is similar to JUnit but it is much more powerful than JUnit but still it’s inspired by JUnit. It is designed to be better than JUnit, especially when testing integrated classes. Pay special thanks to Cedric Beust who is the creator of TestNG.
TestNG eliminates most of the limitations of the older framework and gives the developer the ability to write more flexible and powerful tests with help of easy annotations, grouping, sequencing & parameterizing.

Benefits of TestNG
There are number of benefits of TestNG but from Selenium perspective, major advantages of TestNG are :
1) It gives the ability to produce HTML Reports of execution
2) Annotations made testers life easy
3) Test cases can be Grouped & Prioritized more easily
4) Parallel testing is possible
5) Generates Logs
6) Data Parameterization is possible

Test Case Writing
Writing a test in TestNG is quite simple and basically involves following steps:
Step 1 – Write the business logic of the test
Step 2 – Insert TestNG annotations in the code
Step 3 - Add the information about your test (e.g. the class names, methods names, groups names etc…) in a testng.xml file
Step 4 - Run TestNG

Annotations in TestNG
@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.

Benefits of using annotations
1) TestNG identifies the methods it is interested in by looking up annotations. Hence method names are not restricted to any pattern or format.
2) We can pass additional parameters to annotations.
3) Annotations are strongly typed, so the compiler will flag any mistakes right away.
4) Test classes no longer need to extend anything (such as Test Case, for JUnit 3).

Wednesday, June 18, 2014

DropDown & Multiple Select Operations

Just like Checkboxes & Radio buttons, Dropdown and Multiple Select also works together and almost the same way. To perform any action, the first task is to identify the element group. They always have a single name but and they contains one or more than one elements in them. I should rather say more than one option in dropdown and multiple select. The only difference between these two is deselecting statement & multiple selections are not allowed on dropdowns. Let’s look at the different operations:

Selecting Dropdown/Multiple Select Box
It is just an ordinary operation like selecting any other type of element on a webpage. You can choose it by ID, Name, css & xpath etc. But to perform any action on this element it is required to import ‘import org.openqa.selenium.support.ui.Select' package and to use it we need to create a new select object of class select.

Select oSelection = new Select(driver.findElement(By.id(id)));
Note: Select class only works for elements with <select> tags

Selecting an option using ‘selectByVisibleText’
It is very easy to choose or select an option given under any dropdowns and multiple selection boxes with selectByVisibleText method.

Select oSelection = new Select(driver.findElement(By.id(id)));

oSelection.selectByVisibleText(text);

Selecting an option using ‘selectByIndex’
It is almost the same as selectByVisibleText but the only difference here is that we provide the index number of the option here rather the option text.

Select oSelection = new Select(driver.findElement(By.id(id)));

oSelection.selectByIndex(index);

Selecting an option using ‘selectByValue’
It is again the same what we have discussed earlier; the only difference in this is that we need to provide the value of the option rather the option text.

Select oSelection = new Select(driver.findElement(By.id(id)));

oSelection.selectByValue(value);

Note: The value of an option and the text of the option may not be always same and there can be a possibility that the value is not assigned to Select webelement. If the value is given in the Select tag then only you can use the selectByValue method.
Getting the Size of Select item
Sometimes you may like to count the element in the dropdown and multiple select box, so that you can use the loop on Select element.

Select oSelection = new Select(driver.findElement(By.id(id)));

List<WebElement> oSize = oSelection.getOptions();

int iListSize = oSize.size();

Printing the Options
All of the above methods work on both Dropdown and Multiple select box.

Select oSelection = new Select(driver.findElement(By.id(id)));

            List oSize = oSelection.getOptions();

            int iListSize = oSize.size();

            for(int i =0; i<iListSize ; i++){

                        String sValue = oSelection.getOptions().get(i).getText();

                        System.out.println(sValue);

                        }

Deselect methods
This only works on Multiple selection boxes. If in case you want to deselect any selected option and that can be done with either deselectAll(), deselectByIndex, deselectByValue and deselectByVisibletext.
Select oSelection = new Select(driver.findElement(By.id(id)));

            oSelection.deselectAll();

            oSelection.deselectByIndex(index);

            oSelection.deselectByValue(value);

            oSelection.deselectByVisibleText(text);

Multiple selection method
This one also just works on Multiple selection boxes and not on regular List boxes or dropdowns. There is no additional logic behind selecting multiple options of Select element. All you need to do is to fire select commands on multiple elements one by one that’s it.

Select oSelection = new Select(driver.findElement(By.id(id)));

            oSelection.selectByIndex(index)

            oSelection.selectByIndex(index)

            // Or

            oSelection.selectByVisibleText(text)

            oSelection.selectByVisibleText(text)

            // Or

            oSelection.selectByValue(value)

            oSelection.selectByValue(value)

CheckBox & Radio Button Operations

Operations on Checkboxes and Radio Buttons are easy to perform and most of the times the simple ID attributes work fine for both of these. But selection and de-selection is not the only thing we want with checkboxes and radio buttons. We might like to check that if the checkbox is already checked or if the radio button is selected by default or anything. Checkboxes and Radio button deals exactly the same way and you can perform below mentioned operations on either of them.

Different Selection Method
By ‘ID’

If ID is given for the radio button/checkbox and you just want to click the radio button/checkbox irrespective of its value, then the command will be like this:
WebElement radioBtn = driver.findElement(By.id("gender"));
 radioBtn.click();

With ‘IsSelected’
If your choice is based on the pre-selection of the Radio button/Checkbox and you just need to select the deselected radio button/checkbox. Assume there are two radio buttons/checkboxes, one is selected by default and you want to select the other one for your test. With IsSelected statement, you can get to know that the radio button or the check box is selected or not.

// Store all the elements of same category in the list of WebLements        
 List  oRadioButton = driver.findElements(By.name("PayBills"));
  // Create a boolean variable which will hold the value (True/False)
 boolean bValue = false;
 // This statement will return True, in case of first Radio button is selected

 bValue = oRadioButton.get(0).isSelected();

 // This will check that if the bValue is True means if the first radio button is selected
 if(bValue = true){

            // This will select Second radio button, if the first radio button is selected by default

            oRadioButton.get(1).click();
 }else{

            // If the first radio button is not selected by default, the first will be selected

            oRadioButton.get(0).click();
 }
Note: Name is always same for the same group of radio buttons/checkboxes but their Values are different. So if you find the checkbox/radio button element with the name attribute then it means that it may contain more than one element, hence we need to use findElements method and store it the list of WebElements.

With ‘Value’
You can even select Radio buttons/Checkboxes with their Values.

// Find the checkbox or radio button element by Name

 List oCheckBox = driver.findElements(By.name("bills"));

  // This will tell you the number of checkboxes are present

 int iSize = oCheckBox.size();

 // Start the loop from first checkbox to last checkboxe

 for(int i=0; i < iSize ; i++ ){

             // Store the checkbox name to the string variable, using 'Value' attribute

             String sValue = oCheckBox.get(i).getAttribute("value");

              // Select the checkbox it the value of the checkbox is same what you are looking for

             if (sValue.equalsIgnoreCase("check")){

                         oCheckBox.get(i).click();

                         // This will take the execution out of for loop

                         break;
                         }
            }

By ‘CssSelector’
A simple way of selecting a check-box or radio button is by using its value:

WebElement oCheckBox = driver.findElement(By.cssSelector("input[value='PayBills']"));

 oCheckBox.click();