Tuesday 8 July 2014

How to navigate URL, Back and forward using selenium webdriver


-> Navigate URL

If we want to naviagte another URL from current URL then we can use below commands for navigate URL.

driver1.navigate().to("www.gmail.com")


-> Back

If we want to back from the current URL same as click "back" button in browser, then we can use below commands.

driver1.navigate().back();


-> forward


If we want to forward from the current URL same as click "forward" button in browser, then we can use below commands.

driver1.navigate().back();

Generate alert in selenium webdriver (using JavascriptExecutor)


-> We can use JavaScriptExecuter for generate alert in selenium webdriver

-> JavaScriptExecuter is very helpful interface in selenium webdriver, because we can use JavaScriptExecuter for run any type of Java script commands.

-> But generating alert in selenium webdriver is rare case for create Automation script. We can use below code for generate alert,


@Test
 public void test () throws InterruptedException
 {
  //Generating Alert Using Javascript Executor
  JavascriptExecutor javascript = (JavascriptExecutor) driver;
  javascript.executeScript("alert('Test Case Execution Is started');");
  Thread.sleep(3000);
  driver.switchTo().alert().accept();
 }

How to store Text of the element in selenium wedriver (using getText())



-> We can use getText() method used to display only the text with in the tag.

-> Its display all text contains with in any tag or element. Its wont display anything if there is not text available.


Example 1:

<a id="SHO">
<span lang="VIDEOS">arunrajvdm</span>
</a>

o/p (web page) arunrajvdm (link)

String ans=driver1.findElement(By.linkText("arunrajvdm")).getText()
System.out.println("Get Videos="+ans);


o/p (Selenium) : arunrajvdm (text)




Example 2:

<li id="li25">
 <b class="font-10">
  <span lang="LBLSKU">This is</span>
  :
 </b>
  official blogger
</li>


o/p (web Page)  This is official blogger


String ans=driver1.findElement(By.id("li25")).getText()
System.out.println("Get Videos="+ans);


o/p (Selenium) : This is official blogger (text)

Its display all the text message with in the <li> tag. So getText() used to display conatins all text with in the tag



Example 3:


<select name="SelectNUmber" class="form-drop">
<option selected="selected" title="1">1</option>
<option  title="2">2</option>
<option  title="3">3</option>
<option  title="4">4</option>
<option  title="6">6</option>

</select>


Code:

Str1=driver1.findElement(By.xpath("//td[3]/select")).getText();
System.out.println("All the TExt ="+Str1);

O/p
All the TExt = 1
2
3
4
6



Example 4:

<select name="SelectNUmber" class="form-drop">
<option selected="selected" title="1">1</option>
<option  title="2">2</option>
<option  title="3">3</option>
<option  title="4">4</option>
<option  title="6">6</option>

</select>


Code:

Str1=driver1.findElement(By.tagName("select")).getText();
System.out.println("All the TExt ="+Str1);


O/p
All the TExt = 1
2
3
4
6

Difference between Click() and Submit() in Selenium



-> Both click() and submit() both are used to click Button in Web page.

-> Selenium Webdriver has one special method to submit any form and that method name Is submit(). submit() method works same as clicking on submit button.


When to use .click() method :

-> You can use .click() method to click on any button.There is no restriction for click buttons.

-> That means element's type = "button" or type = "submit", .click() method will works for both.

-> If button is inside <form> tag or button is outside <form> tag, the click() method will work.



When to use .submit() method :

-> we can use .submit() method for only submit form after click on button.

-> That means element's type = "submit" and button should be inside <form> tag, then only submit() will work.

-> if element's type = "button" means submit() will not work.

-> If button outside of the <form> tag means submit() will not work


For Example, Submit() will work if submit button should be inside <form> tag and element type="submit" as below

<form>
<input id="submitbutton" name="submitbutton" type="submit" value="Next step" class="g-button g-button-submit">
</form>


But click() method will work for all  buttons in webpage with out any restrictions.

Timeout and Expected condition in Selenium Webdriver using JUnit



Sometimes we need to set timeout condition in your test or we need to mention expected consition in selenium webdriver



Timeout Test In JUnit For WebDriver

-> The timeout function used onlt in @Test annotation.
-> Supposing you have written test for one module and you wants to set timeout for your test.
-> Here timeout means allowed maximum time to complete full test.
-> Here Execution allowed for mentioned timeout value. After that mentioned timeout value,it will skip remaining stpes and marked the function as error in console.

Example :

@Test(timeout=1000)
 public void test1(){  
 }

From above example, it will allow 1000 milli sec for execution.

if it will take more than 1000 milli sec for execution means it will skip remaining stes inside the function. And come out from test1() function and test1() marked as error.



Expected Exception Test In JUnit For WebDriver

-> some times we are expecting some exception during your webdriver test execution and that exception which is acceptable.
-> If you are using junit framework for your webdriver test then you can do it very easily.
-> We can specify expected exception condition with @Test annotation as bellow.

@Test(expected = NullPointerException.class)
 public void exceptiontest2() {
 }

Here my expected exception is null pointer exception so my expected condition is NullPointerException.class. You can write your expected exception like IndexOutOfBoundsException.class, ArithmeticException.class, etc.


Example :

@Test(timeout=2000)
 public void test1() throws InterruptedException{
 driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest2 class-test1");
 System.out.print("\njunittest2 class-test1 executed before sleep");
 Thread.sleep(5000);
 System.out.print("\njunittest2 class-test1 executed after sleep");
 }

 @Test
 public void exceptiontest1() {
     throw new NullPointerException();
 }

 @Test(expected = NullPointerException.class)
 public void exceptiontest2() {
  throw new NullPointerException();
 }



Console Output :

Browser open
junittest2 class-test1 executed before sleep
Browser close

-> test1() method is display with error because test was time out after 2000 milisecond as per our condition.
-> exceptiontest2() pass successfully because we have placed expected exception condition with it.
-> exceptiontest1() display with error because there was not any expected exception condition.

How to ignore/exclude test in webdriver using Junit



-> We can use @ignore inbuilt annotation will help us to ignore specific method from test for execution.
-> We need to put @Ignore annotation in test before @Test method which we want to exclude

Example:

If we want to ignore/exclude below test from execution. we need to put @ignore annotation in test before @Test method



package JuintPackage;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Junit_Test1 {

WebDriver driver1=new FirefoxDriver();

@Before
public void beforetest()
{
driver1.manage().window().maximize();
driver1.get("http://google.com");
}

@After
public void aftertest()
{
driver1.quit();
}


@Test
public void Execute_Process()
{

driver1.findElement(By.linkText("Gmail")).click();
}

// ignore below test from execution

@ignore
@Test
public void Execute_SecondProcess()
{

driver1.findElement(By.linkText("Images")).click();
}

}



From above example using @ignore annotation we can ignore/exclude Execute_SecondProcess() method from execution.

Click the Element inside the Span using selenium webdriver



1) If we want to work with any operation inside the span, its better to use xPath to identify the element.

2) if we want to click link by using below coding inside spane mean

<span> Mobiles & Accessories </span>

Then you should use the xPath to find the element, because those text is inside the span.

The below code is used to click the above web element in selenium webdriver

driver1.findElement(By.xPath("/html/body/div[4]/div[3]/div/div/div/div/ul/li[3]/span")).click();

Implement Junit Framework in selenium Webdriver


1) Prework: ( Setup JUnit Framework in eclipse)

Generally you do not need to install junit with eclipse if you have already added external jar files of webdriver  with eclipse. Because required jar file for junit will be already there with webdriver jar files while download from this site -> http://docs.seleniumhq.org/download/.

-> Before using Junit framework in our selenium, we need to make sure JUnit external Jar files are added in eclipse in below path.

Right click on your project -> Build Path -> Configure build path

It will open java build path window. In that window, go to Libraries tab. Here you will see all your jar files. In jar file tree view, look for the jar file name which is starting with junit.


-> If above required .jar file is not added in eclipse means then we need to download and add .jar file in this link -> http://junit.org/



2) Create JUnit Test Case.

We need to create JUnit testcase and will add to our package using below steps in eclips.

i) Right click on "src" -> new -> package-> create new package (EX: JuintPackage)
ii) Right click on above created package -> new -> other-> java-> JUnit-> JUnit test case -> create new testcase java file (Ex:JUnit_Test1.java)


And use use below code for JUnit  testcase as JUnit_Test1.java inside the package JuintPackage.


package JuintPackage;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Junit_Test1 {

WebDriver driver1=new FirefoxDriver();

@Before
public void beforetest()
{
driver1.manage().window().maximize();
driver1.get("http://google.com");
}

@After
public void aftertest()
{
driver1.quit();
}


@Test
public void Execute_Process()
{

driver1.findElement(By.linkText("Gmail")).click();
}

}




And save the above test case.


iii) Run above JUnit Test case. 

Eclipse will run your test case using JUnit and on completion of execution, you can see your result in JUnit pane in eclipse.



3) Running JUnit Test suite (Run Multiple JUnit Test case)

When you run junit test suite, eclipse will run all test cases  one by one. When execution completed, you will see output lines in console.


Steps for running JUnit Test Suite

i) Create two Junit Test case by using Step(2). and saved as Junit_Test1 and JUnit_Test2 respectively.

ii) Then use below stesp for create JUnit Test Suite

 Right click on Package -> new -> other-> java-> JUnit-> select JUnit test suite -> give Test Suite name (JUnit_Tests1)-> choose Junit testcases need to be run (Chosse Junit_Test1 and Junit_Test2)-> click Finish


Its automatically create cose as below


package JuintPackage;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ Junit_Test1.class, Junit_Test2.class })
public class Junit_TestSuite1 {

}


if we see above suite class, there are two JUnit annotations added with name @RunWith and @SuiteCLasses

Here,

-> @RunWith annotation will references junit to run test in class

-> @SuiteClasses describes classes included in that test suite.



iii) when you run junit test suite, eclipse will run both test cases (Junit_Test1 and Junit_Test) one by one. When execution completed, you will see bellow given output lines in console.

junittest1 class is executed
junittest2 class-test1 method is executed
junittest2 class-test2 method is executed




Ref: http://software-testing-tutorials-automation.blogspot.com/2014/01/learn-selenium-webdriver-online-free.html

What is Junit Framework in Selenium



What is TestNG and JUnit frameworks?

-> TestNG and JUnit are tools  to help you organize our test.

-> We can define what you want to run before/after tests and we can able to group the tests and reporting them to made easier.


How are TestNG and JUnit frameworks are related to selenium?

-> Those frameworks are usually mentioned with Selenium.

-> Selenium is common testing tool. But selenium combined with any framework (TestNG or JUnit) together do some work. But both are completly different

-> Selenium used connects you to your browser

-> TestNG/JUnit used to organizes the tests




What is JUnit Framework in Selenium Webdriver

-> JUnit is used the most, then TestNG, then FitNesse

-> JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.

-> We have using some JUnit annotations to control the flow and activity of code execution.

-> You must need to insert JUnit annotation inside the java code to execute your test case as junit test case.

-> The important annotations are

1) @Before
2) @Test
3) @After
4) @BeforeClass
5) @AfterClass.



1. @Before Annotation 

-> THe method under @Before annotation will be executed before the moethod written under @Test annotation.
-> Generally method under @Before used to initializing browser or environment related setup.
-> The method under @Before annotation will executed before each @Test annotations. That means if we have four @Test annotaions in your class, then the @Before method will execute four times.



2. @After Annotation

-> The method under @After annotation will execute after completion of @Test method execution.
-> Generally @After annoation used to close the browser and release the memory of object which created in JUnit framework.
-> The method under @After annotation will executed after each @Test annotations. That means if we have four @Test annotaions in your class, then the @After method will execute four times.


3. @Test

-> The method under @Test annotation will execute after completion of @Before method execution.
-> Generallu method under @Test used to write all testing related activity.
-> We can have any number of @Test method in single class.


4. @BeforeClass

-> Methods under @BeforeClass will execute before any one of the test method starts execution.
-> It will execute only once even if there are multiple @Test method in our class.


5. @AfterClass

-> The method under @After class will excute all the completion of @Test methods exection in class.
-> It will execute only once even if there are multiple @Test method in our class.



Difference between @Before and @BeforeClass annotations


-> The method under @Before annotation will executed before each @Test annotations. That means if we have four @Test annotaions in your class, then the @Before method will execute four times.
->

Test method marked with @Before annotation will be executed before the each @Test method. Means if there are 5 @Test methods in your class then @Before test method will be executed 5 times.
Test method marked with @BeforeClass annotation will be executed just before the class. Means @BeforeClass method will be executed only once before the class even if there are 5 @Test methods in your class.


Difference between @After and @AfterClass annotations

Same as @Before annotation, Test method marked with @After annotation will be executed after the each @Test method.
@AfterClass annotation will be executed only once after last @Test method executed.



How to verify java installed in our system




Use below method to know about java installed or not. Also we know about which version of the java installed in System.

1) Goto command Prompt (Type "cmd" in Run)

2) Type below command in command Prompt

c:\users>java -version

and press enter then we can see the below output to know about the Java information from our system


c:\users>java -version
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)

3) If java not there in our system we should download and installed from below link

http://java.com/en/download/index.jsp


How to Exit from loop in QTP



Exits a block of Do...Loop, For...Next, Function, or Sub code.

Syntax for VBScript Exit Statement

Exit Do
Exit For
Exit Function
Exit Sub


The above  Exit statements used for exit from respective block of the statement.

Sub RandomLoop
   Dim I, MyNum
   Do   ' Set up infinite loop.
      For I = 1 To 1000   ' Loop 1000 times.
         MyNum = Int(Rnd * 100)   ' Generate random numbers.
         Select Case MyNum   ' Evaluate random number.
            Case 17: MsgBox "Case 17"
               Exit For   ' If 17, exit For...Next.
            Case 29: MsgBox "Case 29"
               Exit Do   ' If 29, exit Do...Loop.
            Case 54: MsgBox "Case 54"
               Exit Sub   ' If 54, exit Sub procedure.
            End Select
      Next
   Loop
End Sub