Day 1 - Basic Java Tutorials For Selenium WebDriver 1. Datatypes In Java 2. String Class In Java 3. if, if else and nested if else In Java 4. for loop In Java 5. while, do while loops In Java 6. One and two dimensional array In Java 7. Methods In Java 8. Access Modifiers In Java 9. Return Type Of Method In Java 10. Static, Non Static Methods, Variables In Java 11. Object In Java 12. Variable Types In Java 13. Constructor In Java 14. Inheritance In Java 15. Interface In Java 16. ArrayList In Java 17. Hashtable In Java 18. Read-Write Text File In Java 19. Exception handling, try-catch-finally, throw and throws In Java Day 2 - WebDriver Installation And Configuration 1. Introduction of Selenium WebDriver 2. Downloading and installation Of Selenium Webdriver with Eclipse 3. Creating And Running First Webdriver Script --3.1 Running WebDriver In Google Chrome Day 3 - Configure JUnit With WebDriver 4. Downloading and installation Of JUnit with Eclipse --5.1 Creating and running webdriver test with junit --5.2 Creating and running junit test suite with webdriver --6.1 Using JUnit Annotations in webdriver --6.2 @Before/@After VS @BeforeClass/@AfterClass Difference --6.3 Ignoring JUnit Test from execution --6.4 Junit Timeout And Expected Exception Test Day 4 - Generate Test Report Using JUnit 7. Selenium WebDriver Test report Generation using JUnit - 3 Steps Day 5 - Element Locators In WebDriver 8. Different Ways Of Locating Elements In WebDriver Day 5 - WebDriver Basic Action Commands With Example
9. WebDriver Basic Action Commands And Operations With Examples * Open Firefox Browser * Maximizing Browser Window * Open URL In Browser * Clicking On Button * Submitting Form Using .submit() Method * Store Text Of Element * Typing Text In To Text box * Get Page Title * Get Current Page URL * Get Domain Name * Generating Alert Manually * Selecting Value From Dropdown Or Listbox * Deselecting Value From Dropdown Or Listbox * Navigating Back And Forward * Verify Element Present * Capturing Entire Page Screenshot * Generating Mouse Hover Event * Handling Multiple Windows * Verify Element Is Enabled Or Not * Enable/Disable Element * Handling Alert, Confirmation and Prompt popup * Handle Unexpected Alert Day 6 - WebDriver Wait For Examples Using JUnit And Eclipse 10. How to apply implicit wait in selenium WebDriver script 11. WebDriver Examples * Wait For Element * Wait For Text * Wait For Alert * Wait For Title * Wait For Element Visible * Wait For Element Invisible Day 7 - WebDriver Other Examples 12. WebDriver Other Examples * findElement() And findElements() Difference * Generating Log In WebDriver * Creating Object Repository Using Properties File * Extracting All Links From Page * Extracting/Reading Table Data * Handle Dynamic Web Table * Create And Use Custom Firefox Profile In Selenium WebDriver Test * Downloading Files Using Selenium WebDriver * Handling Ajax Auto Suggest Drop List
13. Parameterization/Data Driven Testing 14. Selenium WebDriver Test Day 8 - TestNG Framework Tutorials 15. Introduction Of TestNG 16. TestNG Installation Steps 17. Similarities and Difference Between TestNG and JUnit 18. Create And Run First TestNG-WebDriver Test 19. TestNg annotations with examples 20. Creating And Running WebDriver Test Suit Using testng.xml File --20.1 Creating Single Or Multiple Tests For Multiple Classes --20.2 Creating Test Suite Using Class From Different Packages --20.3 Creating Test Suite Using Selected Or All Packages --20.4 Including Only Selected Test Methods In Selenium WebDriver-TestNg Test --20.5 testng.xml - Include/Exclude Selenium WebDriver Test Package --20.6 testng.xml - Using Regular Expression To Include/Exclude Test Method --20.7 testng.xml - Skip Test Intentionally Using SkipException() --20.8 Data driven Testing using @DataProvider Annotation Of TestNG --20.9 Parallel test execution In multiple browsers using @Parameters annotation Day 9 - WebDriver Assertions With TestNG Hard Assertions 20.1 assertEquals Assertion With Example 20.2 assertNotEquals Assertion With Example 20.3 assertTrue Assertion With Example 20.4 assertFalse Assertion With Example 20.4 assertNull Assertion With Example 20.4 assertNotNull Assertion With Example Soft Assertion 20.4 Applying TestNG Soft Assertion With Example Day 10 Common Functions To Use In WebDriver Test 20.1 Common Function To Compare Two Strings 20.2 Common Function To Compare Two Integers 20.3 Common Function To Compare Two Doubles
1. Datatypes In Java 1.Data types - Basic Java Tutorials For Selenium WebDriver I have received many requests from my blog readers for posting some basic java tutorials which are really required in selenium webdriver. So now I have planned to post some basic java tutorial posts which are really required in selenium webdriver learning and implementation in your project. These tutorials will help you for selenium webdriver interview preparation too. Let we start from different data types In java which we can use in our selenium webdriver test preparation. In java or any other programming languages, data types represents that which type of values can be stored and what will be the size of that value or how much memory will be allocated. There are nearest eight different data types in java like byte, short, int, long, float, double, char, Boolean. byte and short datatypes are not much more useful in selenium webdriver so I am skipping them here to decrease your confusions. int datatype
int data type is useful to store 32 bit integer (Example : 4523) values only. We can not store decimal (Example 452.23) values in int data type. Example : int i = 4523; long datatype long datatype is useful to store 64 bit integer(Example : 652345) values. You can use it when your value is more larger and can not hold it in int. Same as int datatype, we can not store decimal (Example 452.23) values in long datatype Example : long l = 652345; double datatype double datatype is useful to store 64 bit decimal(Example : 56.2354) values. We can store integer (Example 12456) values too in double datatype. Example : double d1 = 56.2354; double d2 = 12456; char datatype char datatype is useful to store single character(Example : 'd'). It can not store more than one (Example 'dd') character in it. Example : char c = 'd'; boolean datatype boolean datatype is useful to store only boolean(Example : true) values. Example : boolean b = true; String Class String is not a data type but it is a class which is useful to store string in variable. Example : String str = "Hello World"; VIEW DIFFERENT FUNCTIONS OF STRING CLASS Created bellow given example for all these datatypes. Run it in your
eclipse and verify results. public class datatypes { public static void main(String[] args) { int i = 4523; //Can store 32 bit integer values only. long l = 652345; //Can store 64 bit integer values only. double d1 = 56.2354; //Can store 64 bit decimal values. double d2 = 12456; //We can use it for integer values too. char c = 'd'; //Can store single character only. boolean t = true; //Can store only boolean values like true or false. String str = "Hello World"; //Can store any string values. System.out.println("Integer Var Is --> "+i); System.out.println("Long Var Is --> "+l); System.out.println("double Var d1 Is --> "+d1); System.out.println("double Var d2 Is --> "+d2); System.out.println("char Var c Is --> "+c); System.out.println("boolean Var b Is --> "+t); System.out.println("boolean Var str Is --> "+str); } } Bellow given result will display in your console at the end of execution. Integer Var Is --> 4523 Long Var Is --> 652345 double Var d1 Is --> 56.2354 double Var d2 Is --> 12456.0 char Var c Is --> d boolean Var b Is --> true String Var str Is --> Hello World 2. String Class In Java 2.String In Java - Tutorials For WebDriver We have learnt about DIFFERENT DATA TYPES IN JAVA In my past post. Now, Many peoples are understanding that String Is also a data type. Let me correct them -> String Is not data type. If string Is not data types then what Is String? This question can be asked by Interviewer too. String Is an Inbuilt class of java. String class has many Inbuilt functions which we can use to perform different actions on string. If you don't know, Let me tell you that we have to work with strings very frequently In selenium WebDriver tests. So you must have knowledge of useful functions of String class to use them In your selenium webdriver
test development. Let us take simple example of String to understand different methods of String class.
public class Strng_Example { public static void main(String[] args) { String st1 = "This World is Very Nice"; String st2 = " And Beautiful."; //Comparing two strings. Return true If both match else return false. System.out.println("st1 equals to st2? -> "+st1.equals(st2)); //Concatenates st2 with st1. System.out.println("Concatenation of st1 and st2 Is -> "+st1.concat(st2)); //Retrieve the 9th Indexed character from string. System.out.println("Character at Index 9 Is -> "+st1.charAt(9)); //Find the length of string. System.out.println("Length Of St1 -> "+st1.length()); //Converting whole string In lower case. System.out.println("String In Lowercase -> "+st1.toLowerCase()); //Converting whole string In upper case. System.out.println("String In uppercase -> "+st1.toUpperCase()); //Retrieve the Index of first 'i' character. System.out.println("Index of 1st charater i Is -> "+st1.indexOf('i')); //Retrieve the index of 2nd most 'i' character. System.out.println("Index of 2nd charater i Is -> "+st1.indexOf('i', 3)); //Retrieve the Index of word 'Very' from string. System.out.println("Index of word Very Is -> "+st1.indexOf("Very")); //Converting value From int to string. int j = 75; String val2 = String.valueOf(j); System.out.println("Value Of string val2 Is -> "+val2); //Converting string to integer. String val1="50"; int i = Integer.parseInt(val1); System.out.println("Value Of int i Is -> "+i);
//Print the String starting from 5th Index to 12th Index. System.out.println("Retrieving sub string from string -> "+st1.substring(5, 13)); //Split string. String splt[] = st1.split("Very"); System.out.println("String Part 1 Is -> "+splt[0]); System.out.println("String Part 2 Is -> "+splt[1]); //Trim String. System.out.println("Trimmed st2 -> "+st2.trim()); } } If you will look at above example, I have prepared different examples of string method to take some action or we can say operations on string. Sort explanation of all above string methods are as bellow. Two String Comparison To compare two strings, we can use syntax like st1.equals(st2). It will return True If both strings are same else It will return False. Two String Concatenation Syntax st1.concat(st2) will concatenate st1 with st2. Retrieving Character from Index Syntax st1.charAt(9)) will retrieve the character from string st1 located at 9th Index. Index Starts from 0. Length Of String st1.length() will return lenght of string st1. Convert String In Lower Case Letters st1.toLowerCase() will convert whole string letters In lower case. Convert String In UpperCase Letters st1.toUpperCase() will convert whole string letters In upper case. Retrieving Index Of 1st most character st1.indexOf('i') will retrieve Index of first most character 'i' from string. Retrieving Index Of 2nd most character st1.indexOf('i', 3)) will retrieve Index of second most character 'i' from string. 3 described the from Index means It will start finding character 'i' from Index 3. First 'i' has Index 2 so we need to use 3 to find 2nd most character. Retrieving Index Of specific word from string st1.indexOf("Very") will retrieve index of word 'Very' from string.
Convert from Integer To String String.valueOf(j) will convert value of 'j' from int to string. Convert from String To Integer Integer.parseInt(val1) will conver value of 'val1' from string to int. Retrieving sub string from string Syntax st1.substring(5, 13) will retrieve string from Index 5 To Index 13. Split String String splt[] = st1.split("Very") will split string st1 from word 'Very' and store both strings In array. Trim String If string has white space at beginning or end of the string then you can use trim function like st2.trim() to remove that white space. 3. if, if else and nested if else In Java
If Else Statement - Basic Java Tutorials For Selenium WebDriver In my PREVIOUS POST, we have seen different data types in java. It is very important to learn basic java tutorials If you wants to learn selenium webdriver with Java. Because If you do not have knowledge of basic java then you can not create single logical webdriver test case. And also you can not pass any company interview. So keep your eyes on these tutorials and I will take you from basic to advanced java tutorials step by step. In this post, Let me tell you the usage of If else conditional statements in java. if, if else and nested if else statements are useful to take the decision based on conditional match.When you wants to execute some part of code if condition returns true then you need to use this kind of conditional statements. Simple If Statement Part of code will be executed only if specified condition returns true. If condition will return false then that code will be not executed. Example : if (i
If else Statement If condition returns true then part of if block will be executed. If condition returns false then part of else block will be executed. Example : if (i>=j) { System.out.println("Value Of i("+i+") Is Greater Than Or Equals To Value Of j("+j+")." ); }else { System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." ); } In above given example, if block's message will be printed if value of variable i is greater than or equals to value of variable j. else block will be executed if value of variable i is less than value of variable j. Nested If Else Statements You can use nested if else statement when you wants to check multiple conditions and take decision based on it. Example : if (k
=i && k<=j) { System.out.println("Value Of k("+k+") Is In Between Value Of i("+i+") And Value Of Value Of j("+j+")" ); }else { System.out.println("Value Of k("+k+") Is Greater Than Value Of j("+j+")" ); } In above given example, first (if) block will be executed if value of variable k is less than the value of variable i. Second (else if) block will be executed if value of variable k is greater than or equals to value of variable i and less than or equals to value of variable j. Third (else) block will be executed if value of variable k is greater than value of value of variable j. You can make a chain of if else statement if you wants to check more conditions. This way, You can use any of above conditional statement based on your requirement. Run bellow given example in your eclipse by changing the values of variables.
public class IfStatements { public static void main(String[] args) { int i = 25; int j = 50; int k = 24; //Simple If statement System.out.println("***Simple If Statement Example***"); if (i=j)//Bellow given message will be printed if value of variable i is greater than or equals to value of variable j. { System.out.println("Value Of i("+i+") Is Greater Than Or Equals To Value Of j("+j+")." ); }else//Bellow given message will be printed if value of variable i is less than value of variable j. { System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." ); } //Nested If Else Statement System.out.println(""); System.out.println("***Nested If Else Statement Part***"); if (k=i && k<=j)//Bellow given message will be printed if value of variable k is greater than or equals to value of variable i and less than or equals to value of variable j. { System.out.println("Value Of k("+k+") Is In Between Value Of i("+i+") And Value Of Value Of j("+j+")" ); }else //Bellow given message will be printed if value of variable k is greater than value of variable j. {
System.out.println("Value Of k("+k+") Is Greater Than Value Of j("+j+")" ); } } } Bellow given output will be printed in your eclipse console when you will run above example. ***Simple If Statement Example*** Value Of i(25) Is Smaller Than Value Of j(50). ***If Else Statement Example*** Value Of i(25) Is Smaller Than Value Of j(50). ***Nested If Else Statement Part*** Value Of k(24) Is Less Than Value Of i(25)
4. for loop In Java for Loop - Basic Java Tutorials For Selenium WebDriver We have learnt different if else condition statements in my PREVIOUS POST. Now let we move to loops in java. Loops(for loop, while loop, do while loop) have very important role in selenium webdriver test case development with java or any other languages. As you know, sometimes you need to perform same action multiple times(Example : 100 or more times) on your web page. Now if you will write multiple lines of code to perform same action multiple times then it will increase your code size. For the best practice, you need to use loops in this kind of situations. Let me describe you for loop in this post and you can view my NEXT POST for reading about while loop. for Loop There are three parts inside for loop. 1. Variable Initialization, 2. Condition To Terminate and 3. Increment/Decrements variable. for loop will be terminated when condition to terminate will becomes false. Example : for(int i=0; i<=3; i++){ System.out.println("Value Of Variable i is " +i); } Bellow given example is simple example of for loop. run it in your eclipse
and verify the result. public class forloop { public static void main(String[] args) { for(int i=0; i<=3; i++){ //This loop will be executed 4 times System.out.println("Value Of Variable i is " +i); } System.out.println(""); int i=0; int k = 200; for(int j=3; j>=i; j--){ //This loop will be executed 4 times System.out.println("Value Of Variable j is " +j); k = k-10; } System.out.println(""); System.out.println("Value Of Variable k is " +k); } } When you will run above given example, you will get bellow given output. Value Value Value Value
Of Of Of Of
Variable Variable Variable Variable
i i i i
is is is is
0 1 2 3
Value Value Value Value
Of Of Of Of
Variable Variable Variable Variable
j j j j
is is is is
3 2 1 0
Value Of Variable k is 160 5. while, do while loops In Java while, do while Loops - Basic Java Tutorials For Selenium WebDriver As we have learnt in my PREVIOUS POST, loops(for loop, while loop) in java or any other programming languages are useful to execute block of code multiple times. You will have to use loops in your selenium webdriver test very frequently. We have already learnt for loop with different examples in my previous post. Now let me describe you while loop and do while loop with practical examples. while Loop
Block of code which is written inside while loop will be executed till the condition of while loop remains true. Example : int i = 0; while(i<=3){ System.out.println("Value Of Variable i Is "+i); i++; } In above given example, while loop will be executed four times. do while Loop Same as while loop, do while loop will be executed till the condition returns true. Example : int j=0; do{ System.out.println("Value Of Variable j Is "+j); j=j-1; }while(j>0); In above given example, while loop will be executed only one time. Difference between while and do while loop There is one difference between while and do while loop.
while loop will check condition at the beginning of code block so It will be executed only if condition (while(i<=3)) returns true.
do while loop will check condition at the end of code block so It will be executed minimum one time. After 1st time execution, it will check the condition and if it returns true then code of block will be executed once more or multiple time.
Disadvantage of while or do while loop If you will forget to Increment or decrements variable value inside while loop block then block of code will be executed infinite time. Example : int i = 0; while(i<=3){ System.out.println("Value Of Variable i Is "+i); } Above given while loop will be executed infinite time because variable is not incremented inside while loop block. Bellow given full example of while and do while loops will clear out your all doubts. Simple run it in your eclipse and verify result. public class Whileloop {
public static void main(String[] args) { //while loop - will be executed till condition returns true. System.out.println("***while loop example***"); int i = 0; //Variable initialization while(i<=3){ System.out.println("Value Of Variable i Is "+i); i++;//Incrementing value of i by 1. } //do while loop - will be executed minimum one time without considering condition. System.out.println(""); System.out.println("***do while loop example***"); int j=3; //Variable initialization do{ System.out.println("Value Of Variable j Is "+j); j=j-1;//Decrementing value of j by 1; }while(j>=0); } } Output of above given example will be as bellow. ***while loop example*** Value Of Variable i Is 0 Value Of Variable i Is 1 Value Of Variable i Is 2 Value Of Variable i Is 3 ***do Value Value Value Value
while loop example*** Of Variable j Is 3 Of Variable j Is 2 Of Variable j Is 1 Of Variable j Is 0
6. One and two dimensional array In Java Arrays - Basic Java Tutorials For Selenium WebDriver What is Array? As we have learnt in my post about DIFFERENT DATA TYPES, We can store values in variables based on type of data like int i=5; double d = 12.254; etc. Now if you wants to store multiple values (10 or 15 or more different values) in different variables then it will be overhead for you to create and initialize different variables for each value. In this situation, you can use array to store multiple different values in array. An array can store multiple value of
same data type(int, char, String) at the same time and each stored data location has unique Index. There are two types of array as bellow. One Dimensional Array
Above given Image describes one dimensional array having one row of data. One dimensional array is just like spreadsheet with data in one row. As shown in above Image, Index of array Is starting from 0. Means value 10 has Index 0, 12 has Index 1 and so on and each value can be Identified by Its Index. We can create and Initialize values In array as shown In bellow given example. public class Array_Example { public static void main(String[] args) { int a[] = new int[6]; //Array declaration and Creation. 6 is length of array. a[0] = 10; //initialize 1st array element a[1] = 12; //initialize 2nd array element a[2] = 48; //initialize 3rd array element a[3] = 17; //initialize 4th array element a[4] = 5; //initialize 5th array element a[5] = 49; //initialize 6th array element for(int i=0; i
Two Dimensional Array
Tow dimensional array is just like spreadsheet with multiple rows and columns having different data in each cell. Each cell will be Identified by it's unique row and column Index combination(Example str[5][3]). We can use two dimensional array to store user id and password of different users as shown in above Image. For above given example Image, We can create and initialize values in two dimensional array as shown in bellow given example. public class Twodimarray { public static void main(String[] args) { String str[][] = new String[3][2]; //3 rows, 2 columns str[0][0]="User1"; str[1][0]="User2"; str[2][0]="User3"; str[0][1]="Password1"; str[1][1]="Password2"; str[2][1]="Password3"; for(int i=0; i
String str[][] = {{"User1","Password1"},{"User2","Password2"}, {"User3","Password3"}}; 7. Methods In Java Methods In Java - Tutorials For Selenium WebDriver What Is Method? In Selenium webdriver test suite, You need to perform some actions multiple time or in multiple test cases like Login in to Account, Place Order or any other action. If you will write this kind of (same repeated) actions In all the test cases then It will becomes overhead for you and will Increase size of your code. Instead of that, If you create methods for this kind of operations and then call that method whenever required then It will be very easy to maintain your test cases. Method Is group of statements which is created to perform some actions or operation when your java code call it from main method. Code written Inside methods can not be executed by It self. To execute that method code block, You need to call that method inside main method block. Let me give you simple example of how to create a method and how to call It from main method block. Simple Method Example : public class Methodexample { public static void main(String[] args) { Test1(); //Test1() method called inside main method. } public static void Test1(){ //Simple Method - Called from main method. System.out.println("Test1 Method Executed."); } public static void Test2(){ //Simple Method - Not called from main method. System.out.println("Test2 Method Executed."); } } If you will run above example then console output will looks like bellow. Test1 Method Executed. As per the console output, We can say that Test1() method is executed but Test2() method is not executed because It Is not called from main method.
Methods will have bellow given different components. 1. Visibility Of Method : You can set your method's visibility by providing access modifier keywords like public, private, protected at beginning of method. VIEW DETAILED EXAMPLE. Example : public static void Testing_Nomod(){ //public method //Block of code } 2. Return Type Of Method : Any method can have return types like int, String, double etc.. based on returning value's data type. void means method is not returning any value. VIEW EXAMPLE OF RETURN TYPE Example : public int Return_Type(){ //This method has int return type. int i=10; return i; } 3. Static or non static method : Method can be static or non static. If you wants to keep your method as static then you need to use static keyword with method. If you wants to create non static method then do not write static keyword with method. VIEW FULL DESCRIPTION ON STATIC AND NON STATIC. Example : public void My_Method1(){ //Non static Method //Block of code } public static void My_Method2(){ //Static Method //Block of code } 4. Method Name : You can give any name to your method. Always use method name relative to its functional work. Example : public static void Login(String user, String Pass){ //Login is the method name. //Block of code } 5. Input Parameters To Method : We can pass Input parameters to any
method. Need to write parameter with its data type. VIEW EXAMPLE OF INPUT PARAMETERS Example : public static void Student_Details(int Rollno, String Name){ //Rollno and Name are input parameters preceded by their data types //Block of code } 8. Access Modifiers In Java Access Modifiers In Java - Java Tutorials For Selenium WebDriver Access modifiers are the keywords in java by which we can set the level of access for class, methods, variables and constructors. There are 4 different access modifiers available in java. Now let me try to describe you how can we use them to set the access for the methods and variables. First of all let me tell you meaning of each access modifier keyword and then will give you examples for them.
public : We can access public methods or variables from all class of same package or other package.
private : private methods and variables can be accessed only from same class. We can not access It from other classes or sub classes of even same package.
protected : protected methods can be accessed from classes of same package or sub classes of that class.
No Access Modifier : If method have not any access modifier then we can access It Inside all class of same package only.
Now let me show you practical difference between all these 4 access modifiers. I have created 3 classes as bellow. Two(Accessmodif, Access) of them are in same package Test_Package1 and one class (Accessing) is in other package named Test_Package2 of same project. Class Accessing is child class of Accessmodif class. package Test_Package1; public class Accessmodif { public static int i=10; private static String str="Hello"; protected static double d=30.235;
static char c='g'; public static void main(String[] args) { Testing_pub(); Testing_pri(); Testing_pro(); Testing_Nomod(); } //Method with public access modifier. Can be accessible by any class. public static void Testing_pub(){ System.out.println("Testing_pub() Executed"); System.out.println("Value Of i Is "+i); System.out.println("Value Of str Is "+str); System.out.println("Value Of d Is "+d); System.out.println("Value Of c Is "+c); } //Method with private access modifier. Can be accessible from same class only. private static void Testing_pri(){ System.out.println("Testing_pri() Executed"); } //Method with protected access modifier. Can be accessible from any class of same package or sub class of this class. protected static void Testing_pro(){ System.out.println("Testing_pro() Executed"); } //Method with no access modifier. Can be accessible by all classes of same package Only. static void Testing_Nomod(){ System.out.println("Testing_Nomod() Executed"); } } package Test_Package1; public class Access { public static void main(String[] args) { Accessmodif.Testing_pub(); //Can access public methods outside the class or package. //Accessmodif.Testing_pri(); - Can not access private methods outside the class Accessmodif.Testing_pro(); //Can access protected methods inside same package class.
Accessmodif.Testing_Nomod(); //Can access no modifier methods inside same package class. System.out.println(); System.out.println("Value Of i Is "+Accessmodif.i); //Can access public variables outside the class or package. //System.out.println("Value Of str Is "+Accessmodif.str); - Can not access private variables outside the class System.out.println("Value Of d Is "+Accessmodif.d); //Can access protected variables inside same package class. System.out.println("Value Of c Is "+Accessmodif.c); //Can access no modifier variables inside same package class. } } package Test_Package2; import Test_Package1.Accessmodif; public class Accessing extends Accessmodif{ public static void main(String[] args) { Testing_pub(); //Can access public methods outside the package. //Testing_pri(); - Can not access private methods outside the class. Testing_pro(); //Can access protected methods inside child class. //Testing_Nomod(); - Can not access no access modifier methods outside the package. System.out.println(); System.out.println("Value Of i Is "+i); //Can access public variables outside the package. //System.out.println("Value Of str Is "+str); - Can not access private variables outside the class. System.out.println("Value Of d Is "+d); //Can access protected variables inside child class. //System.out.println("Value Of c Is "+c); - Can not access no access modifier variables outside the package. } } As per above example, Now its clear that based on access modifiers, we can access variables, methods, etc.. in any other package or class. If you will un comment the commented methods or variables from above given classes, It will show you error related to access level. 9. Return Type Of Method In Java Return Type Of Method In Java - Tutorials For Selenium WebDriver
We have learnt METHOD IN JAVA and different METHOD ACCESS MODIFIERS in my previous posts. Now let me introduce you with different return types of methods in java. You can use two kind of return types with methods. 1. Void and 2. Any data types. Void means returning nothing and when your method is returning some values like Integer, String, double, etc.., You need to provide return type with method according to returning value's data types.
int, String, double etc..Data types - If method is returning any value then you need to provide return type with method like int, String, Double etc..
void - If method is not returning any value then you can give void as return type. void means method returning nothing.
Let me give you simple example of int, double and void return type. package Test_Package1; public class Return_Types { static int c; static double d; public static void main(String[] args) { Mul(2,3); Div(7,3); System.out.println("Value of c Is "+c); System.out.println("Value of d Is "+d); Message(); } //This method is returning integer value. It's return type is int. public static int Mul(int a, int b){ c=a*b; return c; } //This method is returning double value. It's return type is double. public static double Div(double a, double b){ d=a/b; return d; } //This method is returning nothing so there is used void return type. public static void Message(){ System.out.println("Test Message"); } } If you see in above example, I have used three methods (Mul, Div and Message) and called all three methods in main method to execute them.
Method Mul is returning multiplied integer value in variable c so I have used int data type as return type with Mul method.
Method Div is returning division of two values in variable d so I have used double data type as return type with Div method.
Method Message is returning nothing so I need to use void return type with It.
10. Static, Non Static Methods, Variables In Java Java Tutorials For Selenium WebDriver - Static And Non Static Methods Right now we are learning different components of methods in java as described in THIS POST. You can read about use of different ACCESS MODIFIERS and RETURN TYPES of method If you are not aware about it. One another component of method Is It can be static or non static. Static keyword with method Is describes that this method Is static and If method do not have static keyword then that method Is non static. Same rule Is applied for variables too. Static means stable and non static means unstable in common words. There are several difference between static and not static methods In java as described bellow. Main Difference Between Static And Non Static Methods In Java
We can call static methods directly while we can not call non static methods directly. You need to create and instantiate an object of class for calling non static methods. VIEW THIS POST to learn about object In Java.
Non static stuff (methods, variables) can not be accessible Inside static methods Means we can access only static stuff Inside static methods. Opposite to It, Non static method do not have any such restrictions. We can access static and non static both kind of stuffs Inside non static methods
Static method Is associated with the class while non static method Is associated with an object.
Now Let us look at one simple example of static and non static methods and variables. Bellow given example describes you how to access static and non static stuff Inside static and non static methods of same class or different class. Created Two different class as bellow. package Test_Package1;
public class static_nonstatic { static int wheel = 2; int price = 25000; public static void main(String[] args) { //static method. //Can access static methods directly Inside static method. byke1(); //Can access static variables directly Inside static method. System.out.println("Main static method : wheels = "+wheel); //Can not access non static variables directly inside static method. //System.out.println("Main static method : wheels = "+price); //Can not access non static methods directly inside static method. //byke2(); //Created object of class to access non static stuff Inside static method. static_nonstatic sn = new static_nonstatic(); //Now We can access non static methods of class Inside static methods using object reference. sn.byke2(); //Now We can access non static variables of class Inside static methods using object reference. System.out.println("Main static method : price = "+sn.price); } public static void byke1(){ //static method. //Can access static variables directly Inside static method. System.out.println("byke1 static method : wheels = "+wheel); //Can not access non static variables directly inside static method. //System.out.println(price); } public void byke2(){ //non static method. //Can access static variable directly inside non static method. System.out.println("byke2 Non static method : wheels = "+wheel); //Can access non static variable directly inside non static method. System.out.println("byke2 Non static method : price = "+price); //Can access static methods directly Inside non static method. byke1(); } }
package Test_Package1; public class static_ousideclass { public static void main(String[] args) { //static method. //Can call static function from other class directly using class name. static_nonstatic.byke1(); //Can call static variables from other class directly using class name. System.out.println("Using static variable of other class"+static_nonstatic.wheel); //Created object of class static_nonstatic to access non static stuff from that class. static_nonstatic oc = new static_nonstatic(); //Now We can access non static variables of other class Inside static methods using object reference. System.out.println("Accessing non static variable outside the class : "+oc.price); //Now We can access non static methods of other class Inside static methods using object reference. oc.byke2(); } } As you can see in above examples, we can access only static stuff Inside any static methods directly. If you wants to access static method or variable Inside different class then you can access It using simply class name as shown In above example. You must have to create object of class to access non static method or variable Inside static method (byke1) of same class or different class(main method of 2nd class). On other side, we can access static and non static methods and variables directly inside non static method (byke2). There is not any such access restrictions. 11. Object In Java Selenium WebDriver Java Tutorials - Object In Java What Is An Object In Java?
If Interviewer ask you this question then your answer should be like this : Object Is an Instance of class. In other words we can say object Is bundle of related methods and variables. Every object has Its own states and behavior. Objects are generally used with constructors In java. Understanding of object Is very Important for Selenium WebDriver learner because we have to create and use objects In our test case development. We can create multiple objects for the same class having Its own property. Let us take one real world scenario to understand object clearly. Simplest example Is bicycle Is an object of vehicle class having Its own states and behavior. Same way, motorcycle Is another object of vehicle class. Few properties for both the objects are same like wheels=2, handle=1. Few properties for both the objects are different like price, color, speed etc.. How to create object? You can create object of class vehicle using new keyword as bellow. public class vehicle { public static void main(String[] args) { //Created object for vehicle class using new keyword. //bicycle is the reference variable of this object. vehicle bicycle = new vehicle("Black"); } //Constructor with color parameter passed. It will retrieve value from object vehicle. public vehicle(String color){ //Retrieved value will be printed. System.out.println("Color Of vehicle Is "+color); } } Console Output will looks like bellow when you will run above example. Color Of vehicle Is Black In above example, Used one constructor to pass the value of object. We will look about constructor In my upcoming post. Please remember here one thing - bicycle Is not an object. It Is reference variable of object vehicle. Based on this example, Now we can say that object has three parts as bellow.
Declaration : Variable declaration for object. In this example, bicycle is the reference variable for object.
Instantiation : Object creation using new keyword Is called as Instantiation.
Initialization : Call to a constructor Is known as object initialization.
As described In PREVIOUS POST, You can use object of class to access non static variables or methods of class in different class too. This way you can use object of class and also you can create multiple objects of any class. Bellow given example will show you how to create multiple object of class to pass different kind of multiple values In constructor. public class vehicle { public static void main(String[] args) { //Create 2 objects of class. Both have different reference variables. vehicle bicycle = new vehicle("black", 2, 4500, 3.7); vehicle motorcycle = new vehicle("Blue", 2, 67000, 74.6); } public vehicle(String color, int wheels, int price, double speed){ System.out.println("Color = "+color+", Wheels = "+wheels+", Price = "+price+", Speed = "+speed); } } Output of above program will looks like bellow. Color = black, Wheels = 2, Price = 4500, Speed = 3.7 Color = Blue, Wheels = 2, Price = 67000, Speed = 74.6 12. Variable Types In Java Variable Types In Java - WebDriver Tutorials With Java Before learning about variable types In java, I recommend you to read my posts related to variable's DATA TYPES, ACCESS MODIFIERS and STATIC AND NON STATIC VARIABLES. As you know, Variable provide us a memory space (based on type and size of declared variable) to store a value. There are different three types of variables available In java as bellow. 1. Local Variables
Variables which are declared Inside methods or constructor are called as local variables for that method or constructor.
Variables declared Inside method or constructor are limited for that method or constructor only. You can not access to It outside that method or constructor.
You can not use access modifiers with local variables because they are limited to that method or constructor block only.
Need to initialize the value of local variables before using It because there Is not any default value assigned to local variables.
2. Instance Variables (Non Static)
Instance variables are declared on class level which is parallel to methods or constructors (outside the method or constructor block).
Instance variables are generally used with objects. So they are created and destroyed with object creation and destruction.
Instance(non static) variables are accessible directly by all the non static methods and constructors of that class.
If you wants to access Instance(non static) variables Inside static method, You needs to create object of that class.
Instance variables are always Initialized with Its default values based on Its data types.
You can access Instance variable directly (by Its name) Inside same class. If you wants to access It outside the class then you have to provide object reference with variable name.
Vast usage of Instance variables in java programs and selenium webdriver tests.
3. Class Variables (Static)
Same as Instance variables, Class variables are declared on class level (outside the method or constructor block). Only difference Is class variables are declared using static keyword.
Class variables are used In rare case like when It Is predefined that value of variable will never change. In that case we can use class variables.
Class variables are created on program start and destroyed on program end.
Class variables are visible to all methods and constructors of class. Class variables are visible to other class based on Its access modifiers. Generally they are public.
We can access class variables directly using Its name Inside same class. If you wants to access It outside the class then you need to use class name with variable.
Bellow given example will give you some Idea about all three types of variables. Created two class to show you how to access class variable inside other class. Both these class will show you the access levels of all three types of variables. public class Collage1 { //Class Variables - Collage name will be same for both departments so declared as class(static) variable. public static String Collage_Name = "A1 Collage"; //Instance Variables private String Department = "Computer Engineering"; private String name; private double percentile; public static void main(String[] args) {//Static Method //Can access class variable directly If needed. i.e. Collage_Name Collage1 student1 = new Collage1("Robert"); student1.setPercentage(67.32); student1.print_details(); //Can access Instance variable using object reference If needed. //Example : student1.name = "Robert"; Collage1 student2 = new Collage1("Alex"); student2.setPercentage(72.95); student2.print_details(); } public Collage1(String student_name){//Constructor //Can access Instance variable directly Inside constructor. name = student_name; } public void setPercentage(double perc){ //Can access Instance variable directly Inside non static method. percentile = perc; } public void print_details(){ int Year = 2014; //Local Variable - Can not access It outside this method. System.out.println("Resultg Of Year = "+Year); System.out.println("Student's Collage Name = "+Collage_Name); System.out.println("Student's Department = "+Department); System.out.println("Student's Name = "+name); System.out.println("Student's percentile = "+percentile+"%"); System.out.println("**********************"); } }
Console output will looks like bellow. Resultg Of Year = 2014 Student's Collage Name = A1 Collage Student's Department = Computer Engineering Student's Name = Robert Student's percentile = 67.32% ********************** Resultg Of Year = 2014 Student's Collage Name = A1 Collage Student's Department = Computer Engineering Student's Name = Alex Student's percentile = 72.95% ********************** public class Collage2 { private String Department = "Mechanical Engineering"; private String name; private double percentile; public static void main(String[] args) { Collage2 student1 = new Collage2("Smith"); student1.setPercentage(57.35); student1.print_details(); } public Collage2(String student_name){ name = student_name; } public void setPercentage(double perc){ percentile = perc; } public void print_details(){ int Year = 2014; System.out.println("Resultg Of Year = "+Year); //Can access other class's class variable using that class name. System.out.println("Student's Collage Name = "+Collage1.Collage_Name); System.out.println("Student's Department = "+Department); System.out.println("Student's Name = "+name); System.out.println("Student's percentile = "+percentile+"%"); System.out.println("**********************"); } } Console output will looks like bellow.
Resultg Of Year = 2014 Student's Collage Name = A1 Collage Student's Department = Mechanical Engineering Student's Name = Smith Student's percentile = 57.35% **********************
13. Constructor In Java Selenium WebDriver Java Tutorials : Constructors What Is Constructor In Java? If interviewer asks you a definition of constructor then you can give him answer like : Constructor Is a code block which Is Called and executed at the time of object creation and constructs the values (i.e. data) for object and that's why It Is known as constructor. Each class have default no argument constructor In Java If you have not specified any explicit constructor for that class.In java, Constructor looks like methods but bellow given properties of constructor are differentiate them from the methods. You can VIEW TUTORIALS OF METHODS IN JAVA. Constructor Creation Rules
Name of the constructor must be same as class name. Means If your class name Is Student then constructor name must be Student.
Constructor must have not any return types.
Same as methods, We can pass parameters to constructors. Let me show you simple example of parameterized cunstructor In java. You can also view my PREVIOUS POST to see the example of constructor. public class Student { public static void main(String[] args) { //Two different objects created with value. Student stdn1 = new Student("Michael"); Student stdn2 = new Student("Robert"); } //Constructor with parameter to pass values of object //Name of constructor Is same as class name. public Student(String name){ String stdnname = name; System.out.println("Student's Name Is "+stdnname); }
} Console output will looks like bellow. Student's Name Is Michael Student's Name Is Robert In above example, Constructor will be called at the time of objects creation. Constructor will pass the values of objects one by to print them. Constructor Overloading As we know, Constructors name must be same as class name, When you create more than one constructors with same name but different parameters In same class Is called constructor overloading. So question Is why constructor overloading Is required? Constructor overloading Is useful when you wants to construct your object In different way or we can say using different number of parameters. You will understand It better when we will look at simple example but before that let me tell some basic rules of constructor overloading.
Two constructors with same arguments are not allowed for constructor overloading.
You need to use this() keyword to call overloaded constructor.
If you are calling constructor from overloaded using this() keyword, It must be first statement.
It is best practice to call constructor from overloaded constructor to make It easy to maintain.
constructor
Bellow given example shows best example of constructor overloading. public class Student { String finame;//Instance variable String miname;//Instance Variable public static void main(String[] args) { Student stdn1 = new Student("Jim"); Student stdn2 = new Student("Mary", "Elizabeth"); } //Constructor with one argument. public Student(String fname){ finame = fname;//Local Variable System.out.println("1. First Name Is "+finame); } //Overloaded Constructor with two arguments. public Student(String fname, String mname){ finame = fname;
miname = mname; System.out.println("2. First Name Is "+finame); System.out.println("2. Middle Name Is "+miname); } } Console output will looks like bellow. 1. First Name Is Jim 2. First Name Is Mary 2. Middle Name Is Elizabeth We can do same thing using single object creation too using this() keyword as bellow. public class Student { String finame; String miname; public static void main(String[] args) { Student stdn2 = new Student("Mary", "Elizabeth"); } //Constructor with one argument. public Student(String fname){ finame = fname; System.out.println("1. First Name Is "+finame); } //Overloaded Constructor with two arguments. public Student(String fname, String mname){ this("Jim"); //1st constructor Is called using this keyword. finame = fname; miname = mname; System.out.println("2. First Name Is "+finame); System.out.println("2. Middle Name Is "+miname); } } If you will run above example then console's output will be same but you can see we have created only one object Inside main method. Used this keyword In overloaded constructor to call another constructor. 14. Inheritance In Java Inheritance In Java : Tutorials For Selenium WebDriver Till now we have learnt many tutorials on java like Methods, Access Modifiers, Static and Non Static, Object, Constructor, and Many More Tutorials On Java... All these java object oriented concept tutorials are very
much useful in selenium webdriver test case development. That's why I recommend you all to learn them very carefully. All these tutorials will also helps you to pass selenium webdriver Interview. Now let me take you one step ahead to Inheritance In java. What Is Inheritance In Java? Inheritance(parent-child) Is very useful concept of java object oriented programming language by which we can reuse the code of parent class. Inheritance Is providing us a mechanism by which we can inherit the properties of parent class In to child class. Example : Audi class Is child class of Car class then Audi class can access/use all the non private properties (methods, variables..etc) of Car class. Using Inheritance, we can reuse the code of parent class In to child class so that size of code will decrease. Maintenance of code will be also very easy. VIEW EXAMPLE OF USING INHERITANCE IN SELENIUM WEBDRIVER extends keyword Is used to Inherit child class from parent class. Let me show you very simple example of Inheritance In java. In this example, Car class Is parent class of Audi class so all the non private properties of Car class are Inherited and able to use In Audi class. Parent Class public class Car {//Car Class Is Parent Class Of Audi Class private String type="Vehicle"; public static int wheels = 4; public String color = "blue"; String fuel = "Petrol"; public String getfuel(){ return fuel; } protected void Seats(){ int seat = 4; System.out.println("Car Seats = "+seat); } } Child Class or Sub Class public class Audi extends Car{//Audi Is child Class Of Car Class. public int speed=150; public static void main(String[] args) { Audi A = new Audi(); A.printdetails();
//Can access instance variable of parent class using object reference of child class Inside static methods. System.out.println("Color Of Audi = "+A.color); //Can access non static method of parent class using object reference of child class Inside static methods. System.out.println("Fuel Of Audi = "+A.getfuel()); } public void printdetails(){ //Can access class variables of parent class directly Inside child class non static methods. System.out.println("Wheels Of Audi = "+wheels); System.out.println("Speed Of Audi = "+speed); //Can access non static methods of parent class directly Inside child class non static methods. Seats(); //Can not access private variable of parent class In child class. //System.out.println("Wheels Of Audi = "+type); } } Output of above example will looks like bellow. Wheels Of Audi = 4 Speed Of Audi = 150 Car Seats = 4 Color Of Audi = blue Fuel Of Audi = Petrol If you will study above example carefully, You can understand It easily that In child class, we can access only non private members of parent class. This Is just basic example of Inheritance In Java. Overriding In sub class, When you create a method with same signature, return types and arguments of parent class's method then that sub class's method Is known as overridden method and It Is called as overriding In java. Overriding Is useful to change to the behavior of parent class methods. Let me show you simple example of method overriding In java. Consider same above given example. Generally all cars have 4 seats so we have created Seats() method with 4 seat variable. But supposing ford car has 6 seats and I wants to print 6 seats for Ford car. In this case we can use method overriding In Ford class as bellow. For this example, Consider Car class of above example as parent class of Ford class. Here method Seats() Is overridden In sub class. public class Ford extends Car{//Ford Is child Class Of Car Class. public static void main(String[] args) {
Car C = new Ford();//Created Ford Class object with Car Class reference. C.Seats(); } //Parent class method Seats Is overridden In child class. protected void Seats(){ int seat = 6; System.out.println("Audi Seats = "+seat); } } Output of above example will looks like bellow. Audi Seats = 6 Here, method of sub class Is called at place of parent class. Another main thing to notice here Is we have created object of child class but reference Is given of parent class. 15. Interface In Java Interface In Java : Tutorials For Selenium Webdriver I described about Inheritance and method overriding In my PREVIOUS POST so I am suggesting you to read that post, Specially method overriding concept before learning about Interface In Java. If you will go for selenium webdriver Interview then Interviewer will ask you first question : What Is WebDriver? Peoples will give different different answers but right answer Is WebDriver Is an Interface. So It Is most Important thing for all selenium webdriver learner to understand an Interface properly. What Is An Interface And Why To Use It? Using Interface, We can create a contract or we can say set of rules for behavior of application. Interface Is looks like class but It Is not class. When you implements that Interface In any class then all those Interface rules must be applied on that class. In sort, If you Implement an Interface on class then you must have to override all the methods of Interface In your class. Interface will create Rules To Follow structure for class where It Is Implemented. This way, If you look at the code of Interface, You can get Idea about your program business logic. When you are designing big architecture applications like selenium webdriver, You can use Interface to define business logic at Initial level. Interface can be Implemented with any class using implements keyword. There are set of rules to be followed for creating an Interface. Let me tell you all these rules first and then give you an example of an Interface.
Interface can not hold constructor.
Interface can not hold instance fields/variables.
Interface can not hold static methods.
You can not instantiate/create object of an Interface.
Variables Inside Interface must be static and mandatory to initialize the variable.
Any class can Implement Interface but can not extend Interface.
Can write body less methods Inside Interface.
By default all the methods and variables of Interface are public so no need to provide access modifiers.
How To Add Interface In Your Project To add Interface In your project, Right click on package and go to -> New -> Interface. It will open New java Interface popup. Give any name to Interface(Example : College) and click on save button. It will add College.java Interface file under your package.
Now let us look at simple example of Interface.
Create One Interface file with name = College.java as shown In bellow example.
Create 3 class file with name = Computer.java, Mechanical.java and TestCollege.java as shown In bellow example.
College.java public interface College {//Interface file //Initialized static variable. //No need to write static because It Is by default static. String Collegename = "XYZ"; //Created non static methods without body. void StudentDetails(); void StudentResult(); } Computer.java //Class file Implemented with Interface file using implements keyword. public class Computer implements College { //@Override annotation describes that methods are overridden on interface method. //Methods name, return type are same as methods of an Interface. @Override public void StudentDetails() { System.out.println("Computer Dept. Student Detail Part"); } @Override public void StudentResult() { System.out.println("Computer Dept. Student Result Part"); } } Mechanical.java //Class file Implemented with Interface file using implements keyword. public class Mechanical implements College{ @Override public void StudentDetails() { System.out.println("Mechanical Dept. Student Detail Part"); } @Override public void StudentResult() {
System.out.println("Mechanical Dept. Student Result Part"); } } TestCollege.java public class TestCollege {//Class file. No need to implement Interface. public static void main(String[] args) { //Can access Interface variable directly using Interface name. System.out.println(College.Collegename+" Collage student details."); //Created Computer class object with reference of interface College. College compdept = new Computer(); //Methods will be called from Computer class. compdept.StudentDetails(); compdept.StudentResult(); //Created Mechanical class object with reference of interface College. College mecdept = new Mechanical(); //Methods will be called from Mechanical class. mecdept.StudentDetails(); mecdept.StudentResult(); } } Now If you will run TestCollege.java file, Output will looks like bellow. XYZ Collage student details. Computer Dept. Student Detail Part Computer Dept. Student Result Part Mechanical Dept. Student Detail Part Mechanical Dept. Student Result Part Selenium WebDriver And Interface Simple example of Interface In selenium WebDriver Is WebDriver Interface. When you are Initializing any browser using selenium WebDriver, You are writing statements like bellow. WebDriver driver = new FirefoxDriver(); Or WebDriver driver = new ChromeDriver(); You can view more examples of selenium WebDriver on THIS PAGE. Here, WebDriver Is Interface and FirefoxDriver and ChromeDriver are the class files where WebDriver Interface Is Implemented. 16. ArrayList In Java
WebDriver Tutorial : ArrayList Class In Java In THIS POST, I have described about one and two dimensional array In Java. Then question Is what Is arraylist In java and why we need It? Interviewer can ask you this question then you can give him answer like : arraylist Is a class that Implements list Interface In java which supports dynamic array means size of array can grow as needed. As you know, We can create only fixed size array to store values Inside It and that Is the limitation/drawback of array because when you don't know how many values you needs to store In array then how can you provide/define size of array? ArrayList helps us to overcome this limitation of array because It can re-size automatically by Itself. So finally we can say that when you don't know how many values you have to store In array, You can use ArrayList at place of simple array. We have to use arraylist many times In our selenium webdriver test case development. Example : Store all links from page, store all buttons Id from page etc.. In all such case, You will not aware about how many values you have to store. VIEW NEXT POST to learn about hashtable In Java for selenium webdriver Bellow given example will show you how to create and work with arraylist class In java. Same thing we will use In selenium WebDriver test case development to store values. //Import ArrayList class header file import java.util.ArrayList; public class ArrayList_Example { public static void main(String[] args) { //Create object of ArrayList class. It will store only string values. ArrayList Sample = new ArrayList(); //Now you can store any number of values In this arraylist as bellow. Size constrain will comes never. Sample.add("button1"); //Putting an Item In arraylist at Index = 0. Sample.add("button2"); //Putting an Item In arraylist at Index = 1. Sample.add("button3"); //Putting an Item In arraylist at Index = 2. Sample.add("button4"); //Putting an Item In arraylist at Index = 3. for(int i=0; i
System.out.println("Index Of button3 Item = "+ItemIndex); System.out.println("*************************"); Sample.remove(1);//To remove an Item from arraylist. for(int i=0; i t1 = new Hashtable();
t1.put("Legs", 4); //Store value 4 In key = Legs t1.put("Eyes",2); //Store value 2 In key = Eyes t1.put("Mouth",1); //Store value 1 In key = Mouth //Accessing hash table values using keys. System.out.println("Animal Legs = " +t1.get("Legs")); System.out.println("Animal Eyes = " +t1.get("Eyes")); System.out.println("Animal Mouth = " +t1.get("Mouth")); } } Need More Tutorials On Java And Selenium WebDriver? VISIT THIS PAGE As you see In above example, I have created object of Java Hashtable class and then store values with Its unique keys. Then I have used keys to access and print Its values. This way we can store and access values from hash table whenever required. 18. Read-Write Text File In Java Read-Write Text File In Java - Tutorials For WebDriver We have learnt about String class and Its different functions In my PREVIOUS POST. Now our next topic Is How to write In to text file or How to read text file In java. Many times you will need reading or writing text file In your selenium webdriver test case development. For Example, You are reading some large data from web page and wants to store It In text file to use It somewhere else In future. Same way, You have to read data from file for some purpose. It Is very easy to Create, Write and read text file In java. We can use java built in class File to create new file, FileWriter and BufferedWriter class to write In to file, FileReader and BufferedReader class to read text file. Bellow given example will first of all create temp.txt file In D: drive and then write two line In to It. Then It will read both lines one by one from text file using while loop and print In console. You can use bellow given example code for reading or writing text file In your selenium webdriver test case whenever needed. import import import import import import
java.io.BufferedReader; java.io.BufferedWriter; java.io.File; java.io.FileReader; java.io.FileWriter; java.io.IOException;
public class RW_File {
public static void main(String[] args) throws IOException { //Create File In D: Driver. String TestFile = "D:\\temp.txt"; File FC = new File(TestFile);//Created object of java File class. FC.createNewFile();//Create file. //Writing In to file. //Create Object of java FileWriter and BufferedWriter class. FileWriter FW = new FileWriter(TestFile); BufferedWriter BW = new BufferedWriter(FW); BW.write("This Is First Line."); //Writing In To File. BW.newLine();//To write next string on new line. BW.write("This Is Second Line."); //Writing In To File. BW.close(); //Reading from file. //Create Object of java FileReader and BufferedReader class. FileReader FR = new FileReader(TestFile); BufferedReader BR = new BufferedReader(FR); String Content = ""; //Loop to read all lines one by one from file and print It. while((Content = BR.readLine())!= null){ System.out.println(Content); } } } This way we can read and write text file In java for your selenium webdriver test case development. 19. Exception handling, try-catch-finally, throw and throws In Java How To Handle Exception In Java : Tutorials For Selenium WebDriver Anyone don't like exceptions and at the same time, anyone can not hide himself from exceptions when running webdriver tests because (What Is An Exception? :->) exception Is an error event generated during the execution of webdriver test case or java program which disrupts test execution In between. Exception can arise due to the many reasons like, network connection or hardware failure, Invalid data entered by user, DB server down etc.. So all these things can happens any time when you run your selenium webdriver test case and we can not stop It. So Instead of thinking about stopping exception(Which Is not possible) during run time, Think about handling exceptions. Java provides very good exception handling mechanism to recover from this kind of errors. Let us learn different ways of handling exception In java. There are two types of exceptions In java as bellow.
1. Checked Exception : Checked exceptions are those exceptions which are checked during compile time and needs catch block to caught that exception during compilation. If compiler will not find catch block then It will throw compilation error. Very simple example of checked exception Is using Thread.sleep(5000); statement In your code. If you will not put this statement Inside try catch block then It will not allow you to compile your program. 2. Unchecked Exceptions : Unchecked exception are those exception which are not checked during compile time. Generally checked exceptions occurred due to the error In code during run time. Simplest example of unchecked exception Is int i = 4/0;. This statement will throws / by zero exception during run time. Handling exceptions using try-catch block We need to place try catch block around that code which might generate exception. In bellow given example, System.out.println(a[9]); Is written Intentionally to generate an exception. If you see, that statement Is written Inside try block so If that statement throw an exception - catch block can caught and handle It. public class Handle_exce { public static void main(String[] args) { int a[] = {3,1,6}; try { //If any exception arise Inside this try block, Control will goes to catch block. System.out.println("Before Exception"); //unchecked exception System.out.println(a[9]);//Exception will arise here because we have only 3 values In array. System.out.println("After Exception"); }catch(Exception e){ System.out.println("Exception Is "+e); } System.out.println("Outside The try catch."); } } If you will run above example In your eclipse, try block will be executed. "Before Exception" statement will be printed In console and Next statement will generate an exception so "After Exception" statement will be not printed In console and control will goes to catch block to handle that exception. Always use try catch block to log your exception In selenium webdriver reports.
Handling exceptions using throws keyword Another way of handling exception Is using throws keyword with method as shown In bellow given example. Supposing you have a throwexc method which Is throwing some exception and this method Is called from some other method catchexc. Now you wants to handle exception of throwexc method In to catchexc method then you need to use throws keyword with throwexc method. public class Handle_exce { public static void main(String[] args) { catchexc(); } private static void catchexc() { try { //throwexc() Method called. throwexc(); } catch (ArithmeticException e) { //Exception of throwexc() will be caught here and take required action. System.out.println("Devide by 0 error."); } } //This method will throw ArithmeticException divide by 0. private static void throwexc() throws ArithmeticException { int i=15/0; } } In above given example, Exception of throwexc() Is handled Inside catchexc() method. Using throw Keyword To Throw An Exception Explicitly Difference between throw and throws In java : As we learnt, throws keyword Is useful to throw those exceptions to calling methods which are not handled Inside called methods. Throw keyword has a different work - throw keyword Is useful to throw an exception explicitly whenever required. This Is the difference between throw and throws In java. Interviewer can ask this question. Let us look at practical example. public class Handle_exce { public static void main(String[] args) { catchexc(); } private static void catchexc() { try { //throwexc() Method called.
throwexc(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array Index out of bound exception."); } } private static void throwexc() { //This statement will throw ArrayIndexOutOfBoundsException exception. throw new ArrayIndexOutOfBoundsException(); } } In above example, ArrayIndexOutOfBoundsException exception will be thrown by throw keyword of throwexc method. finally keyword and Its use finally keyword Is used with try catch block at the end of try catch block. Code written Inside finally block will be executed always regardless of exception Is occurred or not. Main intention of using finally with try catch block Is : If you wants to perform some action without considering exception occurred or not. finally block will be executed In both the cases. Let us see simple example of finally. public class Handle_exce { public static void main(String[] args) { try{ int i=5/0; //Exception will be thrown. System.out.println("Value Of i Is "+i);//This statement will be not executed. }catch (Exception e)//Exception will be caught. { System.out.println("Inside catch."+e);//print the exception. }finally//finally block will be executed. { System.out.println("Inside finally. Please take appropriate action"); } try{ int j=5/2; //Exception will be not thrown. System.out.println("Value Of j Is "+j);//This statement will be executed. }catch (Exception e)//No exception so catch block code will not execute. { System.out.println("Inside catch."+e); }finally//finally block code will be executed. { System.out.println("Inside finally. Please take appropriate action"); } }
} In above example, 2 try-catch-finally blocks used. Run above example and observe result. 1st try block will throw an error and catch will handle and then finally block will be executed. 2nd try block will not throw any error so catch will be not executed but finally block will be executed. So In both the cases finally block will be executed. So all these things about exception and ways of handling them will helps you In your webdriver test exception handling. Posted by P Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
1. Introduction of Selenium WebDriver What is selenium webdriver What is selenium webdriver and how it help us in software testing process? Webdriver in selenium (http://docs.seleniumhq.org/projects/webdriver/) is an Interface and it is designed to overcome some limitations of selenium RC software testing tool. However selenium WebDriver's development is in process so still there are few limitations and known issues available in
selenium WebDriver. Selenium WebDriver is also known as Selenium 2 and used for web as well mobile applications testing. It is freeware software testing tool and mostly used as a regression testing tool for web and mobile applications. Selenium 2 supports most of all browsers to run your test cases and many programming languages like C#, Java, Python, Ruby, .Net, Perl, PHP, etc.. to create and modify your test scripts. Selenium 2(WebDriver) controls browser directly from operating system level so it is interacting very fast and with more realistic way with browsers. Major people in world using Selenium webdriver with java. Difference between WebDriver and selenium RC WebDriver
Selenium WebDriver do not require selenium server for running test.
WebDriver is using native automation from each and every supported language for running automation scripts on browsers.
WebDriver supports web as well mobile application testing so you can test mobile applications (iPhone or Android).
Supporting latest versions of almost all browsers.
WebDriver controls the browser itself.
Selenium RC
Required selenium server for running test.
Selenium RC is using JavaScripts to drive automation with browser.
Selenium RC supports only web application testing.
Supporting all browsers but not supporting latest versions.
Selenium RC is using javascript to interact and operate on web page
You can share if you know any limitations or advantages of Selenium WebDriver by posting comments bellow. Click here to read more about WebDriver. You can read my next post about selenium webdriver download install. selenium web driver, selenium webdriver documentation, selenium
testing, webdriver selenium, selenium testing tool, selenium driver, selenium tool, automated testing tools, software testing tools, selenium automation, selenium webdriver vs remote control, selenium online training, selenium training, selenium test, selenium test tool, webdriver, automated testing tools, web testing tools, test automation tools, selenium firefox webdriver 2. Downloading and installation Of Selenium Webdriver with Eclipse List of Selenium Commands With Examples Part - 1 Selenium IDE commands with examples There are many commands available in selenium IDE. I have prepared one selenium commands list and linked some selenium ide command with its examples. So you can click on command link(From bellow given selenium ide commands list table) to view how to and where to use that command with example. This full selenium command list will help you to learn selenium IDE on beginning level. (Do you wants to be master of selenium IDE in just 7 days? If yes then Read this Selenium IDE tutorials) Pending command's(Which are not linked) example creation is in process. you can subscribe via email for new post update or you can bookmark this page in your browser to visit it again. SUBSCRIBE VIA EMAIL TO GET ALL COMMAND EXAMPLES VIA EMAIL Complete List of Selenium IDE Commands (Click here to view part 2) addLocationStrategy addLocationStrategyAndWait addScript addScriptAndWait addSelection addSelectionAndWait allowNativeXpath allowNativeXpathAndWait altKeyDown altKeyDownAndWait altKeyUp altKeyUpAndWait answerOnNextPrompt assertAlert assertAlertNotPresent assertAlertPresent
assertAllButtons assertAllFields assertAllLinks assertAllWindowIds assertAllWindowNames assertAllWindowTitles assertAttribute assertAttributeFromAllWindows assertBodyText assertChecked assertConfirmation assertConfirmationNotPresent assertConfirmationPresent assertCookie assertCookieByName assertCookieNotPresent assertCookiePresent assertCursorPosition assertEditable assertElementHeight assertElementIndex assertElementNotPresent assertElementPositionLeft assertElementPositionTop assertElementPresent assertElementWidth assertEval assertExpression assertHtmlSource assertLocation assertMouseSpeed assertNotAlert assertNotAllButtons assertNotAllFields assertNotAllLinks assertNotAllWindowIds assertNotAllWindowNames assertNotAllWindowTitles assertNotAttribute assertNotAttributeFromAllWindows assertNotBodyText assertNotChecked assertNotConfirmation assertNotCookie assertNotCookieByName assertNotCursorPosition assertNotEditable assertNotElementHeight
assertNotElementIndex assertNotElementPositionLeft assertNotElementPositionTop assertNotElementWidth assertNotEval assertNotExpression assertNotHtmlSource assertNotLocation assertNotMouseSpeed assertNotOrdered assertNotPrompt assertNotSelectOptions assertNotSelectedId assertNotSelectedIds assertNotSelectedIndex assertNotSelectedIndexes assertNotSelectedLabel assertNotSelectedLabels assertNotSelectedValue assertNotSelectedValues assertNotSomethingSelected assertNotSpeed assertNotTable assertNotText assertNotTitle assertNotValue assertNotVisible assertNotWhetherThisFrameMatchFrameExpression assertNotWhetherThisWindowMatchWindowExpression assertNotXpathCount assertOrdered assertPrompt assertPromptNotPresent assertPromptPresent assertSelectOptions assertSelectedId assertSelectedIds assertSelectedIndex assertSelectedIndexes assertSelectedLabel assertSelectedLabels assertSelectedValue assertSelectedValues assertSomethingSelected assertSpeed assertTable assertText
assertTextNotPresent assertTextPresent assertTitle assertValue assertVisible assertWhetherThisFrameMatchFrameExpression assertWhetherThisWindowMatchWindowExpression assertXpathCount assignId assignIdAndWait break captureEntirePageScreenshot captureEntirePageScreenshotAndWait check checkAndWait chooseCancelOnNextConfirmation chooseOkOnNextConfirmation chooseOkOnNextConfirmationAndWait click clickAndWait clickAt clickAtAndWait close contextMenu contextMenuAndWait contextMenuAt contextMenuAtAndWait controlKeyDown controlKeyDownAndWait controlKeyUp controlKeyUpAndWait createCookie createCookieAndWait deleteAllVisibleCookies deleteAllVisibleCookiesAndWait deleteCookie deleteCookieAndWait deselectPopUp deselectPopUpAndWait doubleClick doubleClickAndWait doubleClickAt doubleClickAtAndWait dragAndDrop dragAndDropAndWait dragAndDropToObject dragAndDropToObjectAndWait dragdrop
dragdropAndWait echo fireEvent fireEventAndWait focus focusAndWait goBack goBackAndWait highlight highlightAndWait ignoreAttributesWithoutValue ignoreAttributesWithoutValueAndWait keyDown keyDownAndWait keyPress keyPressAndWait keyUp keyUpAndWait metaKeyDown metaKeyDownAndWait metaKeyUp metaKeyUpAndWait mouseDown mouseDownAndWait mouseDownAt mouseDownAtAndWait mouseDownRight mouseDownRightAndWait mouseDownRightAt mouseDownRightAtAndWait mouseMove mouseMoveAndWait mouseMoveAt mouseMoveAtAndWait mouseOut mouseOutAndWait mouseOver mouseOverAndWait mouseUp mouseUpAndWait mouseUpAt mouseUpAtAndWait mouseUpRight mouseUpRightAndWait mouseUpRightAt mouseUpRightAtAndWait open
openWindow openWindowAndWait pause refresh refreshAndWait removeAllSelections removeAllSelectionsAndWait removeScript removeScriptAndWait removeSelection removeSelectionAndWait rollup rollupAndWait runScript runScriptAndWait select selectAndWait selectFrame selectPopUp selectPopUpAndWait selectWindow sendKeys setBrowserLogLevel setBrowserLogLevelAndWait setCursorPosition setCursorPositionAndWait setMouseSpeed setMouseSpeedAndWait setSpeed setSpeedAndWait setTimeout shiftKeyDown shiftKeyDownAndWait shiftKeyUp shiftKeyUpAndWait store storeAlert storeAlertPresent storeAllButtons storeAllFields storeAllLinks storeAllWindowIds storeAllWindowNames storeAllWindowTitles storeAttribute storeAttributeFromAllWindows storeBodyText storeChecked
storeConfirmation storeConfirmationPresent storeCookie storeCookieByName storeCookiePresent storeCursorPosition storeEditable storeElementHeight storeElementIndex storeElementPositionLeft storeElementPositionTop storeElementPresent storeElementWidth storeEval storeExpression storeHtmlSource storeLocation storeMouseSpeed storeOrdered storePrompt storePromptPresent storeSelectOptions storeSelectedId storeSelectedIds storeSelectedIndex storeSelectedIndexes storeSelectedLabel storeSelectedLabels storeSelectedValue storeSelectedValues storeSomethingSelected storeSpeed storeTable storeText storeTextPresent storeTitle storeValue storeVisible storeWhetherThisFrameMatchFrameExpression storeWhetherThisWindowMatchWindowExpression storeXpathCount submit submitAndWait type typeAndWait typeKeys typeKeysAndWait uncheck
How to download and install Selenium Webdriver with Eclipse and Java Step By Step Download selenium webdriver and install selenium webdriver is not much more hard. Actually there is nothing to install except JDK. Let me describe you step by step process of download, installation and configuration of web driver and other required components. You can view my post about "What is selenium webdriver" if you wants to know difference between WebDriver and selenium RC software tool. (Note : I am suggesting you to take a tour of Basic selenium commands tutorials with examples before going ahead for webdriver. It will improve your basic knowledge and helps you to create webdriver scripts very easily. ) Steps To Setup and configure Selenium Webdriver With Eclipse and Java (Note : You can View More Articles On WebDriver to learn it step by step) Step 1 : Download and install Java in your system First of all you need to install JDK (Java development kit) in your system. So your next question will be "how can i download java" Click here to download Java and install it in your system as per given installation guide over there. Step 2 : Download and install Eclipse Download Eclipse for Java Developers and extract save it in any drive. It is totally free. You can run 'eclipse.exe' directly so you do not need to install Eclipse in your system. Step 3 : Download WebDriver Java client driver. Selenium webdriver supports many languages and each language has its own client driver. Here we are configuring selenium 2 with java so we need 'webdriver Java client driver'. Click here to go on WebDriver Java client driver download page for webdriver download file. On that page click on 'Download' link of java client driver as shown in bellow image.
(language-specific client driver's version is changing time to time so it
may be different version when you will visit download page. ) Downloaded 'webDriver Java client driver' will be in zip format. Extract and save it in your system at path D:\selenium-2.33.0. There will be 'libs' folder, 2 jar files and change log in unzipped folder as shown in bellow figure. We will use all these files for configuring webdriver in eclipse.
Step 4 : Start Eclipse and configure it with selenium 2 (webdriver)
Select WorkSpace on eclipse start up
Double click on 'eclipse.exe' to start eclipse. First time when you start eclipse, it will ask you to select your workspace where your work will be stored as shown in bellow image. Create new folder in D: drive with name 'Webdriverwork' and select it as your workspace. You can change it later on from 'Switch Workspace' under 'file' menu of eclipse.
After selecting workspace folder, Eclipse will be open.
Create new project
Create new java project from File > New > Project > Java Project and give your project name 'testproject' as shown in bellow given figures. Click on finish button.
Now your new created project 'testproject' will display in eclipse project explorer as bellow.
Create new package
Right click on project name 'testproject' and select New > Package. Give your package name = 'mytestpack' and click on finish button. It will add new package with name 'mytestpack' under project name 'testproject'.
Create New Class
Right click on package 'mytestpack' and select New > Class and set class name = 'mytestclass' and click on Finish button. It will add new class 'mytestclass' under package 'mytestpack'.
Now your Eclipse window will looks like bellow.
Add external jar file to java build path
Now you need to add selenium webdriver's jar files in to java build path.
Right click on project 'testproject' > Select Properties > Select Java build path > Navigate to Libraries tab
Click on add external JARs button > select both .jar files from D:\selenium-2.33.0.
Click on add external JARs button > select all .jar files from D:\selenium-2.33.0\libs
Now your testproject's properties dialogue will looks like bellow.
That's all about configuration of WebDriver with eclipse. Now you are ready to write your test in eclipse and run it in WebDriver. You can Read My Post about how to write and run your first test in WebDriver. download selenium webdriver, install webdriver, download webdriver selenium, selenium testing, selenium testing tool, how to download selenium webdriver, what is selenium webdriver, webdriver download, selenium webdriver download, selenium automation, selenium download, selenium install, install selenium webdriver, install selenium webdriver in eclipse, eclipse and selenium, java and selenium, how to install a server, selenium driver, how to setup selenium webdriver, download webdriver selenium, selenium webdriver tutorial java
3. Creating And Running First Webdriver Script
Create And Run First Webdriver Script With Eclipse
Run First Webdriver Script You need to install webdriver with eclipse to run your script in webdriver. After installation of webdriver, You need to write a java code in eclipse for your test case of software web application. Let me give you one simple example of creating simple webdriver script. First of all you need to write code as bellow in your 'mytestclass.java' file. You can request(if you wish) this sample code file by submitting comment bellow with your email id.
Now you are ready to run your script from Run menu as shown bellow.
Script Explanation Above script will
open Firefox browser.
Then driver.get syntax will blog.blogspot.in/' in firefox browser.
Then driver.getCurrentUrl() will get the current page URL and it will be stored in variable 'i'. You can do same thing using "storeLocation" command in selenium IDE
And at last, it will print value of variable in console as shown bellow.
open
'http://only-testing-
So this is the simple webdriver script example. You can create it for your own software web application too by replacing URL in above script. We will learn more scripts in detail in my upcoming posts. --3.1 Running WebDriver In Google Chrome Running Selenium Webdriver Test In Google Chrome You can read my THIS POST to know how to run selenium webdriver test of software application in Mozilla Firefox browser. As you know, webdriver support Google Chrome browser too. You need to do something extra for launching webdriver test in in Google chrome browser. Let me describe you steps to launch webdriver test in Google Chrome. Download ChromeDriver server First of all, download latest version of ChromeDriver server for webdriver. You can download it directly from http://code.google.com/p/chromedriver/downloads/list. Current latest version for win32 is chromedriver_win32_2.3 as shown bellow.
Click on that link. It will take you to download page.
Click on link shown above to download chrome driver zip file. On completion of download, extract zip file to D:/ drive. Now in eclipse, create new project with name = 'chromeproject' and create new class with name = 'chromebrowser'. Don't forget to select 'public static void main(String[] args)' method during new java class creation. Write code as shown bellow in class file. You can request this copy of this code by submitting comment bellow this post.
Look in to above image. I set path for Google chrome driver as System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32_ 2.3\\chromedriver.exe"); So now, your test will run in Google chrome browser.
Day 3 - Configure JUnit With WebDriver 4. Downloading and installation Of JUnit with Eclipse How to download and install junit with eclipse step by step
We have already learn how to configure eclipse for webdriver, Creating new project, new package and then adding new class in my one of the previous post. In that post you can see how to add external jars of webdriver in eclipse. Also you can view how to run your first webdriver test in eclipse for better understanding. 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. How to verify that required jar file for junit is in my build path or not For junit jar file verification, Right click on your project -> Build Path -> Configure build path It will open java build path window as shown in bellow image. 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. Java build path window
If this kind of junit jar file is already there then you do not need to install junit jar with eclipse and you are ready to use junit with eclipse. But if junit jar file is not there then you need to add it. Downloading junit jar file Go to http://junit.org/ website -> Click on download and install guide link will redirect the page at junit jar file download and install page. Here you will find the link like "junit.jar". Click on it will redirect to junit jar file downloading page. From this page download the latest version of junit jar file. Installing junit jar file with eclipse Go to java build path window as shown in above figure. Now click on Add External JARs button to add your downloaded junit jar file with eclipse.
After adding junit jar file, click on OK button to close java build path window. Now you are ready to use junit with eclipse for your webdriver test of software application. Click here to view all articles on webdriver. --5.1 Creating and running webdriver test with junit Creating and running webdriver test with junit and eclipse step by step We have already discussed about how to download and install junit in eclipse to run webdriver test in my previous post. Please note that you need to add junit jar file only if it is not available in webdriver jar file folder. If it is already there with webdriver jar file folder then you not need to do anything to create and run junit test. Now let me describe you how to create webdriver test case using junit. Webdriver test case creation using junit and eclipse You are already aware about how to create new project and package in eclipse and if you are not aware then please visit this post page. To create JUnit Test Case, you need to add JUnit Test Case at place of Class inside your package. Look at bellow given image to know how to add JUnit Test Case.
As shown in above image, Select JUnit Test Case from Select a wizard dialog anf then click on Next button. On Next page, Enter your test case name and click on Finish button.
When you add JUnit Test Case, your eclipse project explorer window will looks like bellow given image.
Now replace bellow given code with your original code. package Testjunit; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Mytest { WebDriver driver = new FirefoxDriver(); @Test public void test() {
driver.manage().window().maximize(); System.out.print("Window maximise"); driver.get("http://only-testing-blog.blogspot.in/"); System.out.print("Site Open"); driver.quit(); System.out.print("End of Test"); } } Running webdriver test case using junit in eclipse After replacing above code with your original code, click on Run button in eclipse. It will show you Run As dialog as shown bellow.
Select JUnit Test from Run As dialog and click on Ok button. Eclipse will run your test case using JUnit and on completion of execution, you can see your result in JUnit pane as bellow.
VIEW THIS POST to know how to create and run junit test suite in eclipse. --5.2 Creating and running junit test suite with webdriver
How To Create And Run JUnit Test Suit For WebDriver Test - Step By Step If you are planning to perform regression testing of any application using webdriver then obviously there will be multiple test cases or test classes under your webdriver project. Example - There are 2 junit test cases under your project's package. Now if you wants to run both of them then how will you do it? Simple and easy solution is creating JUnit test suite. If your project has more than 2 test cases then you can create test suite for all those test cases to run all test cases from one place. Before creating junit test suite, you must have to read my post about "How to download and install junit in eclipse" and "How to create and run junit test in eclipse". Now let me describe you how to create junit test suite in eclipse for your junit test case. Step 1 - Create new project and package Create new project in eclipse with name = junitproject and then add new package = junitpack under your project. VIEW THIS POST to know how to create new project and add package in eclipse. Add required external jar files for selenium webdriver. Step 2 - Create 1st Test Case Now create JUnit test case under junitpack package with class name = junittest1 as bellow. VIEW THIS post to know how to create junit test case in eclipse. package junitpack; import import import import
org.junit.Test; org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver;
public class junittest1 { WebDriver driver = new FirefoxDriver(); @Test public void test() throws InterruptedException { driver.manage().window().maximize(); driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte st1 executed"); Thread.sleep(2000); System.out.print("junittest1 class is executed"); driver.quit(); } }
Step 3 - Create 2nd test case Same way, Create 2nd test class with name = junittest2 under package = junitpack as bellow. package junitpack; import import import import import import import
org.junit.After; org.junit.Before; org.junit.Test; org.junit.Ignore; org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver;
public class junittest2 { WebDriver driver = new FirefoxDriver(); @Before public void setup () { driver.manage().window().maximize(); driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); } @After public void aftertest() { driver.quit(); } @Test public void test1() throws InterruptedException{ driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte st2 class-test1"); System.out.print("\njunittest2 class-test1 method is executed"); Thread.sleep(2000); } @Test public void test2() throws InterruptedException { driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte st2 class-test2"); Thread.sleep(2000); System.out.print("\njunittest2 class-test2 method is executed"); } } Step 4 - Create test suite for both test cases
Now we have 2 test cases(junittest1.java and junittest2.java) under package = junitpack. To create test suite, Right click on junitpack package folder and Go to -> New -> Other -> Java -> Junit -> Select 'JUnit Test Suite' as shown in bellow image.
Now click on Next button.On next screen, add junit test suite name = junittestsuite and select both test cases as shown bellow image and then click on Finish button.
It will add new test suite class = junittestsuite.java under your package as bellow. package junitpack; import org.junit.runner.RunWith; import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ junittest1.class, junittest2.class }) public class junittestsuite { } If you see in above suite class, there are 2 junit annotations added with name = @RunWith and @SuiteClasses. @RunWith annotation will references junit to run test in class and @SuiteClasses describes classes included in that test suite. Now your junit test suite is created and project structure will looks like bellow.
Step 4 - Running test suite Select junit test suite class = junittestsuite and run it in eclipse. When you run junit test suite, eclipse will run both test cases (junittest1 and junittest2) one by one. When execution completed, you will see bellow given output lines in console. junittest1 class is junittest2 class-test1 method junittest2 class-test2 method is executed junit test execution report will looks like bellow.
is
executed executed
This way we can create junit test suite to run multiple test cases from one place. You can view all Junit tutorial posts for webdriver on THIS LINK. VIEW MY NEXT POST to know how to ignore test from execution. --6.1 Using JUnit Annotations in webdriver How to Use JUnit Annotations in webdriver test case with example Unit testing framework JUnit has many 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. You can look in my previous post where i have used JUnit @Test annotation before test method. Let me describe you mostly used 3 JUnit Annotations with example. You can view more details on JUnit at http://junit.org/. 1. @Before 2. @Test 3. @After 2 other frequently used annotations are @BeforeClass and @AfterClass. Depending on annotation names, JUnit framework will decide the code execution flow. i.e. First JUnit framework will execute @Before method, Second it will execute @Test method and at last it will execute @After method. 1. @Before Annotation As name suggest. method written under @Before annotation will be executed before the method written under @Test annotation. Based on @Before annotation, JUnit framework will execute that before method first. Generally method under @Before annotation is used to initializing website and other environment related setup. @Before annotation method will be executed before each @Test annotation method means if there are two @Test methods in your class then @Before method will be executed two times. 2. @After
Method under @After annotation is known as after method and execution of @After method will start as soon as completion of @Test method execution completion. Same as @Before , @After annotation method will be executed two times if there are two @Test methods in your class. 3. @Test Method under @Test annotation is known as test method. Execution of @Test method will start as soon as @Before method execution completed. Generally we are writing all testing related activity under @Test. We can use multiple @Test methods in single class too. 4. @BeforeClass Methods under @BeforeClass annotation will be executed before the any test method starts execution. It will be executed only once even if there are multiple @Test methods in your class. 5. @AfterClass @AfterClass method will be run on completion of all the test method's execution from that class. Same as @BeforeClass, @AfterClass method will be executed once only. VIEW EXAMPLE OF DIFFERENCE BETWEEN @Before vs @BeforeClass AND @After VS @AfterClass ANNOTATIONS Execute bellow given example in your eclipse as a debugging mode to verify its execution. package Testjunit; import java.util.concurrent.TimeUnit; import import import import import
org.junit.After; org.junit.Before; org.junit.Test; org.openqa.selenium.*; org.openqa.selenium.firefox.FirefoxDriver;
public class Mytest { WebDriver driver = new FirefoxDriver(); @Before public void beforetest() { driver.manage().window().maximize(); driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); } @After public void aftertest() { driver.quit();
} @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.findElement(By.xpath("//input[@value='Bike']")).click(); boolean str1 = driver.findElement(By.xpath("//input[@value='Bike']")).isSelected(); if(str1 = true) { System.out.print("Checkbox is checked"); } else { System.out.print("Checkbox is not checked"); } } } Here @After method is written before @Test method but JUnit Framework will tells eclipse to execute @Test method first and then @After method --6.2 @Before/@After VS @BeforeClass/@AfterClass Difference Example Of Difference Between @Before/@After VS @BeforeClass/@AfterClass In JUnit With WebDriver Many readers are asking me the difference between JUnit annotations @Before VS @BeforeClass and @After VS @AfterClass in webdriver test. If you have read my JUNIT ANNOTATIONS POST, I have clearly described difference between @Before and @BeforeClass annotations and @After and @AfterClass annotations in bold text. Now let me describe once more and then we will look at practical example for both of them. Difference between @Before and @BeforeClass annotations
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.
Execute bellow given @Before and @After annotations example in your eclipse and observe result in console. package junitpack; import import import import import import import import
org.junit.After; org.junit.AfterClass; org.junit.Before; org.junit.BeforeClass; org.junit.Test; org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver;
public class junittest2 { private static WebDriver driver; @Before public void openbrowser() { System.out.print("\nBrowser open"); driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); } @After public void closebrowser() { System.out.print("\nBrowser close"); driver.quit(); } @Test public void test1() throws InterruptedException{ driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte st2 class-test1"); System.out.print("\njunittest2 class-test1 method is executed"); Thread.sleep(2000); }
@Test public void test2() throws InterruptedException { driver.findElement(By.xpath("//input[@name='fname']")).clear(); driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte st2 class-test2"); Thread.sleep(2000); System.out.print("\njunittest2 class-test2 method is executed"); } } When you execute above example in eclipse, Bellow given result will be displayed in console. Console Output : Browser open junittest2 class-test1 method is executed Browser close Browser open junittest2 class-test2 method is executed Browser close Based on above given console output, we can say each @Before method is executed before each @Test method and each @After method is executed after each @Test method. Now let we replace @Before annotation with @BeforeClass and @After annotation with @AfterClass in same example and then observe result. Replace bellow given @BeforeClass and @AfterClass part with @Before and @After part in above example as bellow. @BeforeClass public static void openbrowser() { System.out.print("\nBrowser open"); driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); } @AfterClass public static void closebrowser() { System.out.print("\nBrowser close"); driver.quit(); } Now run above example and look at console result. Console result will be as bellow. Console Output : Browser open junittest2 class-test1 method is executed
junittest2 class-test2 method is executed Browser close As per console result, we can say @BeforeClass method is executed once only. Same way @AfterClass annotation marked method is also executed once only. --6.3 Ignoring JUnit Test from execution How To Ignore Test In WebDriver With JUnit As described in my PREVIOUS POST, We can create junit test suite to execute multiple test cases from one place. See example of my previous post. junittest2 class have two @Test methods. Now If I wants to exclude/Ignore 1st @Test method from execution and wants to execute only 2nd @Test method then how can I do It? Ignoring specific test in junit test is very easy. @Ignore annotation We can use JUnit's has inbuilt @Ignore annotation before @Test method to Ignore that specific webdriver test from execution. Let we apply @Ignore annotation practically in our test and then observe its execution result. VIEW JUNIT EXAMPLE OF TIMEOUT AND EXPECTED EXCEPTION TEST My scenario is to ignore 1st @Test method from execution so i need to put @Ignore annotation in my test before 1st @Test method as bellow. @Ignore @Test public void test1() throws InterruptedException{ } Here, @Ignore annotation will exclude test1() method from execution. Copy bellow given Ignoring @Test method(test1()) part with @Ignore annotation and replace it will @Test method part given on Step 3 (Create 2nd test case) of THIS EXAMPLE (Note : @Test method part which needs to replace is marked with pink color in that example post). //To ignore this @Test method from execution @Ignore @Test public void test1() throws InterruptedException{ driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte st2 class-test1"); System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000); } Now when you run full test suite(junittestsuite.java) then on completion of junit test suite execution, you will get bellow given result in console. junittest1 class is executed junittest2 class-test2 method is executed As per console result, ignored test(test1()) is not executed. JUnit test execution report will looks like bellow.
This way, Junit's @Ignore annotation will help us to ignore specific test from execution. --6.4 Junit Timeout And Expected Exception Test Example Of Junit Timeout And Expected Exception Test For WebDriver Sometimes you need to set time out for your webdriver test or you need to set expected exception condition for your test. 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. Same way, You are expecting some exception during your webdriver test execution and that exception is acceptable.If you are using junit framework for your webdriver test then you can do it very easily. We have seen example of - how to Ignore specific webdriver test using junit's @Ignore annotation in THIS POST. Now let me describe how to write timeout test and exception test in junit with examples. Timeout Test In JUnit For WebDriver We can specify timeout time with junit's @Test annotation as shown bellow. It will allow maximum 2000 milliseconds to complete the execution of test1() method. After 2000 miliseconds, it will skip remaining execution and test1() will be marked with error. @Test(timeout=2000) public void test1(){
} Expected Exception Test In JUnit For WebDriver We can specify expected exception condition with @Test annotation as bellow. 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, ect. @Test(expected = NullPointerException.class) public void exceptiontest2() { } Junit Example Of Timeout And Expected Exception Test -Go to THIS PAGE -Copy example given on Step 3 - Create 2nd test case and paste it in your eclipse. -Remove all @Test methods from that example and paste bellow given @Test methods and then run your test class (junittest2.java). @Test(timeout=2000) public void test1() throws InterruptedException{ driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junitte st2 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(); } On completion of execution, console will show bellow given out put. Console Output : Browser open junittest2 class-test1 executed before sleep Browser close JUnit test result looks like bellow.
test1() method is display with error because test was time out after 2000 milisecond as per our condition.
exceptiontest2() pass successfully expected exception condition with it.
exceptiontest1() display with error any expected exception condition.
because because
we
have
there
placed
was
not
Day 4 - Generate Test Report Using JUnit 7. Selenium WebDriver Test report Generation using JUnit - 3 Steps Generate webdriver test report in HTML by running build xml file : Part - 3 We have seen how to configure system and eclipse in configuration part 1 and configuration part 2 posts to generate webdriver test report. Now we have a test case and build.xml file in our project tree. Let me describe you few steps of configuring and running build.xml file in eclipse. Now follow the bellow given build.xml file configuration steps to generate HTML report.
Step 1 : Verify build.xml file work space Open External Tools Configuration dialog as bellow Right click on Build.xml - > Run As -> External Tools Configuration. It will open External Tools Configuration dialog as shown bellow.
In Main tab, you need to verify that your current project's build.xml is selected or not.My current project name is "JUnitReport" so it is correct for me. If it is of any other project then you need to change it by clicking on Browse Workspace button.
Step 2 : Set target execution order Go to the target tab and then set target execution order = build, ForReport (My Project name), junitreport. If it is not in this order then you can change it by unchecking and checking and the check box or by clicking on order button. So now my target execution order will looks like bellow.
Step 3 : Set Runtime JRE Go to JRE tab. Here you need to set Runtime JRE = JDK at place of JRE as shown in bellow image.
If JDK is not display in Separate JRE list then you can add it by - Click on Installed JREs button. It will open Preferences dialog. - Click on Add button from Preferences dialog. It will open Add JRE dialog. - Select Standard VM from Add JRE dialog and click on next button as shown in bellow image.
On Next window, Select JDK folder path(Which is located at C:\Program Files\Java\ in my system) In JRE home field and click on Finish button. It will add JDK option in Separate JRE drop down.
Now build file configuration is finished and finally you are ready to run your build.xml file and generate your test report.
Step 4 : Run build.xml Now you can run build.xml file in 3 ways. 1st way : Run from External Tools Configuration dialog as shown.
2nd way : Run directly from build.xml file
3rd way : Run from Menu icons
Step 5 : View Report When you run build.xml file, eclipse will run your junit test case and on completion of execution report file will be generated in your junit folder which is located in your project folder as bellow.
Open index.html file. It will looks like bellow.
Eclipse And Ant Configuration Steps To Generate webdriver test execution report using JUnit : Part - 2 Webdriver test result generation is very important and essential part of automation testing and for that you need to configure your eclipse accordingly. Before eclipse and ant configuration, you need to configure your system as described in Part - 1. Now let me describe you the steps of eclipse configuration to generate web driver test execution report using JUnit. Perform bellow given steps.
Step 1 : Create new JUnit Test Case First of all, you need to create JUnit test case in eclipse as described in JUnit Test Creation Post 1 and Post 2.
Step 2 : Set Ant Home Entries To set ant home entries,
- Go to eclipse Menu -> Window -> Preferences. It will open eclipse preference dialog. - Select Ant -> Runtime from left side preference tree. Now select Classpath at right side. - Select 1st class path Ant Home Entries and click on Ant Home button and select 'apache-ant-1.9.2' folder path and then click on OK as shown in bellow image.
Step 3 : Set junit.jar path in Blobal Entries of Ant Runtime Preference if it is not there As described above, Go to Ant -> Runtime preference settings and select Global Entries. Now click on Add External Jars button and select 'junit.jar' located at eclipse -> plugins -> org.junit_4.11.0.v201303080030 (This folder name may be different if you have different version of junit) -> junit.jar. and then click on OK as shown in bellow image.
Step 4 : Generate build.xml for your project
Now you need to generate build.xml for your project. To generate it, Right click on your project folder and select Export. It will open Export dialog as shown in bellow image.
Select Ant Buildfiles from export dialog and clicking on Next button will show you all your projects list. On Next dialog, select your current project and click on Finish button as shown bellow.
Look in above image. When you will run build.xml file, your test reports will be saved in JUnit output directory = 'junit' folder. It will be created automatically in your project folder when you run build.xml file. We will learn how to run build.xml file in my next post.
When you click on Finish button, build.xml file will be generated inside your project folder as shown bellow.
View my Next Post to see how to configure and run build.xml file to generate your test case report in HTML view.
System Configuration Steps To Generate webdriver test execution report using JUnit : Part -1 Many people facing issues in JUnit report generation configuration using ant and eclipse. If every thing is not setup properly then it will give you one or another error and you will be not able to generate JUnit test case execution report for your web driver test case. Let me describe you few system configuration steps in this post and eclipse configuration steps in my next post to generate JUnit test case execution report very easily and without any error. Step 1 : Download and install latest Java SE Download and install latest Java SE Development Kit (Java development Kit(JDK) and Java Runtime Environment(JRL)) as per your system configuration. You can download it from Java SE Development Kit download page. Step 2 : Download Latest Version of apache-ant zip Download latest version of apache-ant from http://ant.apache.org/bindownload.cgi. Current latest version is apache-ant-1.9.2 as shown in bellow image and it may be different in future.
Extract zip file and save it in your local drive. Step 3 : Steps to Set Environment variables in system property for java - Set JAVA_HOME Environment variable You need to set JAVA_HOME Environment variable in your system property. To set Environment variable, Right click on My Computer -> Properties and go to -> Advanced tab. Clicking on Environment variables button will open Environment variable dialog. Click on New button from System Variables box and add Variable Name = JAVA_HOME and Variable Value = Path of your jdk folder. Here my JDK folder path is 'C:\Program Files\Java\jdk1.7.0_40' as shown in bellow image.
- Set ANT_HOME Environment variable Same as JAVA_HOME Environment variable, Add new system variable name = ANT_HOME and Variable Value = Path of your apache-ant-1.9.2 folder as described in bellow image.
- Edit Path Variable After setting JAVA_HOME and ANT_HOME system variable, Edit existing Path variable by selecting Path variable from System variables list and click Edit button and insert %JAVA_HOME%\bin;%ANT_HOME%\bin at the end of Path variable value string. Do not forget to put semicolon (;) before %JAVA_HOME%\bin as shown in bellow image.
- Copy tools.jar from jdk/lib and paste It In jre/lib
There will be 2 folders In your C:Program Files\Java folder.
In my system It Is jdk1.7.0_40 and jre7.
Open C:\Program Files\Java\jdk1.7.0_40\lib folder and copy tools.jar file.
Open C:\Program Files\Java\jre7\lib and paste tools.jar In to It.
Now restart your system to getting system variables changes effect. Now system configuration is completed for generating webdriver test execution report using JUnit. Now you need to configure eclipse as described in my Day 5 - Element Locators In WebDriver
8. Different Ways Of Locating Elements In WebDriver We have learnt most of all the way of locating element in webdriver like Locating Element By ID, Locating Element By Name, Locating Element By Class Name, Locating Element By Tag Name, Locating Element By Link Text Or Partial Link and Locating Element By CSS Selector How To Locate Elements By ID In Selenium WebDriver With Example Before using WebDriver, You must be aware about different ways of locating an elements in WebDriver. Locating an element is essential part in selenium WebDriver because when you wants to take some action on element (typing text or clicking on button), first you need to locate that specific element to perform action. First of all I recommend you to read all these selenium IDE element locating methods and then read this article about Selenium WebDriver element locators to get all locating methods in better way. WebDriver which is also known as a Selenium 2 has many different ways of locating element. Let me explain each of them with examples. Here I am explaining how to locate element By id and will describe Locating Web Element By ClassName in my Next Post and others in latter posts. Locating UI Element By ID If your webpage element has unique and static ID then you can locate your page element by ID. Look in to bellow given image. You can verify that your webelement has any id or not using the firebug.
In above image, Submit Query button has unique id = 'submitButton'. I can use that id to locate button as bellow. driver.findElement(By.id("submitButton"));
Bellow given example will show you how to locate element by id and then how to click on it. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.(Note : @Test method is marked with pink color in that example). @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); for (int i = 0; i<=20; i++) { WebElement btn = driver.findElement(By.id("submitButton"));//Locating element by id if (btn.isEnabled()) { //if webelement's attribute found enabled then this code will be executed. System.out.print("\nCongr8s... Button is enabled and webdriver is clicking on it now"); //Locating button by id and then clicking on it. driver.findElement(By.id("submitButton")).click(); i=20; } else { //if webelement's attribute found disabled then this code will be executed. System.out.print("\nSorry but Button is disabled right now.."); } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } Selenium Webdriver Element Locator - Locating Element By Name With Example Selenium WebDriver/Selenium 2 is web and mobile application regression testing tool and it is using element locators to find out and perform actions on web elements. We have learn Element Locating by ID, Element Locating By Tag Name and Locating element by Class Name with examples in my previous posts. Locating Element By Name is very useful method and many peoples are using this method in their webdriver automation test case preparation. Locating Element By Name and Locating Element by ID are
nearly same. In Locating Element by ID method, webdriver will look for the specified ID attribute and in Locating Element By Name method, webdriver will look for the specified Name attribute. Let me show you one example of how to locate element by name and then we will use it in our webdriver test case.
Look in to above image, web element 'First Name' input box do not have any ID so webdriver can not locate it By ID but that element contains name attribute. So webdriver can locate it By Name attribute. Syntax of locating element in webdriver is as bellow. driver.findElement(By.name("fname")); Now let we use it in one practical example as bellow.Copy bellow given @Test method part and replace it with the @Test method part of example given on this page. (Note : @Test method is marked with pink color in that example). @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); //Locating element by Name and type given texts in to input box. driver.findElement(By.name("fname")).sendKeys("My First Name"); } Above example will type the text in text box using By Name element locating method. Locating Web Element By ClassName In Selenium WebDriver with example There are many different ways of locating elements in webdriver for your software web application page and I have described one of them in my PREVIOUS POST with example. In webdriver, we can't do any thing on web page if you don't know how to locate an element. As you know, we can use element's ID to locate that specific element but suppose if your element do not have any ID then how
will you locate that element ? Locating web element by className is good alternative if your element contains class name. We can locate element By Tag Name, By Name, By Link Text, By Partial Link Text, By CSS and By XPATH too but will look about them in my next posts. How to get the class name of element You can get the class name of element using firebug as shown in bellow given image.
Look in to above image. Post date content has a class and we can use that class name to store that blog post date string. Notice one more thing in above image, blog post date string has not any ID so we can not locate it by ID. (Note : You can view more webdriver tutorials on THIS LINK.) Example Of Locating Web Element By ClassName We can use bellow given syntax to locate that element. driver.findElement(By.className("date-header")); Practical example of locating web element by className is as bellow. package junitreportpackage; import java.util.concurrent.TimeUnit; import import import import import import import
org.junit.After; org.junit.Before; org.junit.Test; org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.WebElement; org.openqa.selenium.firefox.FirefoxDriver;
public class Mytest1 { //To open Firefox browser
WebDriver driver = new FirefoxDriver(); @Before public void beforetest() { //To Maximize Browser Window driver.manage().window().maximize(); //To Open URL In browser driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); } @After public void aftertest() { driver.quit(); } @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); String datentime = driver.findElement(By.className("dateheader")).getText();//Locating element by className and store its text to variable datentime. System.out.print(datentime); } } In above example, WebDriver driver = new FirefoxDriver() will open webdriver's Firefox browser instance. VIEW THIS POST TO KNOW HOW TO RUN WEBDRIVER TEST IN GOOGLE CHROME. driver.get(); will open targeted URL in browser. Element Locators In Selenium 2 or WebDriver - Locating Element By Tag Name We have learn about Locating element by ID and Locating element by Class Name with examples in my previous posts. Let me repeat once more that if element contains ID then we can locate element by its ID and if element do not have ID and contains Class Name then we can locate an element by Class Name. Now supposing, web element do not have any ID or Class Name then how to locate that element in selenium WebDriver ? Answer is there are many alternatives of selenium WebDriver element locators and one of them is Locating Element By Tag Name.
Locating Element By Tag Name is not too much popular because in most of cases, we will have other alternatives of element locators. But yes if there is not any alternative then you can use element's DOM Tag Name to locate that element in webdriver.
(Note : You can view all tutorials of webdriver element locators) Look in to above image. That select box drop down do not have any ID or Class Name. Now if we wants to locate that element then we can use it's DOM tag name 'select' to locate that element. Element locator sysntex will be as bellow. driver.findElement(By.tagName("select")); Bellow given example will locate dropdown element by it's tagName to store its values in variable. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.(Note : @Test method is marked with pink color in that example). @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); //Locating element by tagName and store its text in to variable dropdown. String dropdown = driver.findElement(By.tagName("select")).getText(); System.out.print("Drop down list values are as bellow :\n"+dropdown); } How To Locate Element By Link Text Or Partial Link Text In Selenium WebDriver In my previous posts what we have learn is we can Locate Element By Name, Locate Element By ID, Locate Element By Class Name And Locate Element By Tag Name to take any action on that element. We will look
about different web driver actions and operations in my upcoming posts. Now let we learn two more element locators as bellow. Locate Element By Link Text If your targeted element is link text then you can use by link text element locator to locate that element. Look in to bellow given image.
My Targeted element Is Link text 'Click Here' and I wants to click on It then I can use It as bellow. driver.findElement(By.linkText("Click Here")).click(); Locate Element By Partial Link Text Same as Link text, We can locate element by partial link text too. In that case we need to use By.partialLinkText at place of By.linkText as bellow. driver.findElement(By.partialLinkText("Click ")).click(); For locating element by link text, we need to use full word 'Click Here' but in case of locating element by partial link text, we can locate element by partial work 'Click' too. Look in to bellow given example. I have used both the element locators to locate links. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page. (Note : @Test method is marked with pink color in that example). @Test public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.findElement(By.linkText("Click Here")).click();//Locate element by linkText and then click on it. WebDriverWait wait = new WebDriverWait(driver, 15); wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("18 :"))); //Locate element by partial linkText. } Selenium WebDriver By.cssSelector Element Locators With Example WebDriver support many different element locating methods and locating element by it's CSS Path is one of the most popular way in webdriver. If you not want to use by id, name, tag name, class name or link text as your locator then you can locate that element by it's CSS path. Read this tutorial to learn different ways of writing CSS path of any element. You can get CSS path of any element using selenium IDE too by setting CSS as your Locator Builders Preference and then performing some action on that element in Selenium IDE recording mode. You can get CSS path of any element by Firebug too. Now let we learn how we can use By.cssSelector in webdriver. Look in to bellow given image.
Here we can locate input box First name using bellow given webdriver syntax. driver.findElement(By.cssSelector("input[name='fname']"));
Bellow given example will locate input box by CSS Selector to type text in it. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page. (Note : @Test method is marked with pink color in that example). @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.findElement(By.cssSelector("input[name='fname']")).sendKeys("My Name");;//Locate element by cssSelector and then type the text in it. } How To Locate Element By XPATH In Selenium 2/WebDriver With Example We have learnt most of all the way of locating element in webdriver like Locating Element By ID, Locating Element By Name, Locating Element By Class Name, Locating Element By Tag Name, Locating Element By Link Text Or Partial Link and Locating Element By CSS Selector. One another method of locating element in selenium webdriver is By XPATH of element. It is most popular and best way to locate element in WebDriver. However you can use other ways too to locate element. You can write Xpath of any element by many different ways as described in This Post.
Above given image shows the firebug view of First name text box. Now let me give you few examples of how to write syntax to locate it in webdriver using xPath in 2 different ways. 1. driver.findElement(By.xpath("//input[@name='fname']")); 2. driver.findElement(By.xpath("//input[contains(@name,'fname')]")); I have used xPath to locate element in above both the syntax. We can use anyone from above to locate that specific element. Let we use it in practical example as bellow. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page. (Note : @Test method is marked with pink color in that example). @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");//Locate element by cssSelector and then type the text in it. }
Selenium css locators tutorial with example As you know, Locators in selenium are main elements and CSS Locator is another alternative of Xpath element locator, ID or Name locator or any other element locators in selenium. Full form of CSS is "Cascading Style Sheets" and it define that how to display HTML elements on webpage. Click here to read more about CSS. There are few advantages and also few disadvantages of using CSS element locators at place of Xpath element locators in selenium. CSS Locators Main Advantage Main advantage of using CSS locator is - It is much more faster and simpler than the Xpath Locators in IE and also they are more readable compared to Xpath locators. Also CSS locators are little faster compared to Xpath locators in other browsers. Note : Need good working examples on selenium IDE? Visit this link for great tutorials on selenium IDE. Now let me come to our main point - How to write CSS locator syntax manually for selenium. I have derived couple of CSS locator syntax with example as bellow. I written CSS locator syntax for three elements(Search text box, Select language drop down and "Go" button) of wikipedia website home page as shown in bellow image.
CSS locator Examples 1. Selenium CSS locator using Tag and any Attribute css=input[type=search] \\\\ This syntax will find "input" tag node which contains "type=search" attribute. css=input[id=searchInput] \\\\ This syntax will find "input" tag node which contains "id=searchInput" attribute. css=form input[id=searchInput] \\\\ This syntax will find form containing "input" tag node which contains "id=searchInput" attribute. (All three CSS path examples given above will locate Search text box.) 2. Selenium CSS locator using Tag and ID attribute css=input#searchInput \\\\ Here, '#' sign is specially used for "id" attribute only. It will find "input" tag node which contains "id=searchInput" attribute. This syntax will locate Search text box. 3. Selenium CSS locator using Tag and class attribute css=input.formBtn \\\\ Here, '.' is specially used for "class" attribute only. It will find "input" tag node which contains "class=formBtn" attribute. This syntax will locate Search button (go). 4. Selenium CSS locator using tag, class, and any attribute css=input.formBtn[name=go] \\\\ It will find "input" tag node which contains "class=formBtn" class and "name=go" attribute. This syntax will locate Search button (go). 5. Tag and multiple Attribute CSS locator css=input[type=search][name=search] \\\\ It will find "input" tag node which contains "type=search" attribute and "name=search" attribute. This syntax will locate Search text box.
6. CSS Locator using Sub-string matches(Start, end and containing text) in selenium css=input[id^='search'] \\\\ It will find input node which contains 'id' attribute starting with 'search' text.(Here, ^ describes the starting text). css=input[id$='chInput'] \\\\ It will find input node which contains 'id' attribute starting with 'chInput' text. (Here, $ describes the ending text). css=input[id*='archIn'] \\\\ It will find input node which contains 'id' attribute containing 'archIn' text. (Here, * describes the containing text). (All three CSS path examples given above will locate Search text box.) 7. CSS Element locator syntax using child Selectors css=div.search-container>form>fieldset>input[id=searchInput] \\\\ First it will find div tag with "class = search-container" and then it will follow remaining path to locate child node. This syntax will locate Search text box. 8. CSS Element locator syntax using adjacent selectors css=input + input \\\\ It will locate "input" node where another "input" node is present before it on page.(for search tect box). css=input + select or css=input + input + select \\\\ It will locate "select" node, where "input" node is present before it on page(for language drop down). 9. CSS Element locator using contains keyword css=strong:contains("English") \\\\ It will looks for the element containing text "English" as a value on the page.
Day 5 - WebDriver Basic Action Commands With Example Selenium WebDriver Tutorials - Basic Action Commands And Operations With Examples I have already posted Selenium WebDrier Tutorials posts how to setup web driver with eclipse and Run first test with webdriver, how to configure junit with eclipse to generate webdriver test report. We have also learn different methods of locating elements in webdriver. All these things are very basic things and you need to learn all of them before starting your test case creation in selenium 2. Now we are ready to learn next step of performing basic actions in web driver with java for your software web application.
VIEW STEP BY STEP TUTORIALS ON SELENIUM WEBDRIVER Today I wants to describe you few basic webdriver commands to perform actions on web element of your web page. We can perform too many command operations in webdriver and will look about them one by one in near future. Right now I am describing you few of them for your kind information. 1. Creating New Instance Of Firefox Driver WebDriver driver = new FirefoxDriver(); Above given syntax will create new instance of Firefox driver. VIEW PRACTICAL EXAMPLE 2. Command To Open URL In Browser driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); This syntax will open specified URL in web browser. VIEW PRACTICAL EXAMPLE OF OPEN URL 3. Clicking on any element or button of webpage
driver.findElement(By.id("submitButton")).click(); Above given syntax will click on targeted element in webdriver. VIEW PRACTICAL EXAMPLE OF CLICK ON ELEMENT 4. Store text of targeted element in variable String dropdown = driver.findElement(By.tagName("select")).getText(); This syntax will retrieve text from targeted element and will store it in variable = dropdown. VIEW PRACTICAL EXAMPLE OF Get Text 5. Typing text in text box or text area. driver.findElement(By.name("fname")).sendKeys("My First Name"); Above syntax will type specified text in targeted element. VIEW PRACTICAL EXAMPLE OF SendKeys 6. Applying Implicit wait in webdriver driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); This syntax will force webdriver to wait for 15 second if element not found on page. VIEW PRACTICAL EXAMPLE OF IMPLICIT WAIT 7. Applying Explicit wait in webdriver with WebDriver canned conditions. WebDriverWait wait = new WebDriverWait(driver, 15); wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath( "//div[@id='timeLeft']"), "Time left: 7 seconds")); Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7 seconds" to be appear on targeted element. VIWE DIFFERENT PRACTICAL EXAMPLES OF EXPLICIT WAIT 8. Get page title in selenium webdriver driver.getTitle(); It will retrieve page title and you can store it in variable to use in next steps. VIEW PRACTICAL EXAMPLE OF GET TITLE 9. Get Current Page URL In Selenium WebDriver driver.getCurrentUrl(); It will retrieve current page URL and you can use it to compare with your expected URL. VIEW PRACTICAL EXAMPLE OF GET CURRENT URL 10. Get domain name using java script executor JavascriptExecutor javascript = (JavascriptExecutor) driver; String CurrentURLUsingJS=(String)javascript.executeScript("return document.domain"); Above syntax will retrieve your software application's domain name using webdriver's java script executor interface and store it in to variable.
VIEW GET DOMAIN NAME PRACTICAL EXAMPLE. 11. Generate alert using webdriver's java script executor interface JavascriptExecutor javascript = (JavascriptExecutor) driver; javascript.executeScript("alert('Test Case Execution Is started Now..');"); It will generate alert during your selenium webdriver test case execution. VIEW PRACTICAL EXAMPLE OF GENERATE ALERT USING SELENIUM WEBDRIVER. 12. Selecting or Deselecting value from drop down in selenium webdriver.
Select By Visible Text
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist"))); mydrpdwn.selectByVisibleText("Audi"); It will select value from drop down list using visible text value = "Audi".
Select By Value
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.selectByValue("Italy"); It will select value by value = "Italy".
Select By Index
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.selectByIndex(0); It will select value by index= 0(First option). VIEW PRACTICAL EXAMPLES OF SELECTING VALUE FROM DROP DOWN LIST.
Deselect by Visible Text
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.deselectByVisibleText("Russia"); It will deselect option by visible text = Russia from list box.
Deselect by Value
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.deselectByValue("Mexico"); It will deselect option by value = Mexico from list box.
Deselect by Index
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.deselectByIndex(5); It will deselect option by Index = 5 from list box.
Deselect All
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); listbox.deselectAll(); It will remove all selections from list box. VIEW PRACTICAL EXAMPLES OF DESELECT SPECIFIC OPTION FROM LIST BOX
isMultiple()
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']"))); boolean value = listbox.isMultiple(); It will return true if select box is multiselect else it will return false.VIEW PRACTICAL EXAMPLE OF isMultiple() 13. Navigate to URL or Back or Forward in Selenium Webdriver driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html"); driver.navigate().back(); driver.navigate().forward(); 1st command will navigate to specific URL, 2nd will navigate one step back and 3rd command will navigate one step forward. VIEW PRACTICAL EXAMPLES OF NAVIGATION COMMANDS. 14. Verify Element Present in Selenium WebDriver Boolean iselementpresent = driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0; It will return true if element is present on page, else it will return false in variable iselementpresent. VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT PRESENT. 15. Capturing entire page screenshot in Selenium WebDriver File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
It will capture page screenshot and store it in your D: drive. VIEW PRACTICAL EXAMPLE ON THIS PAGE. 16. Generating Mouse Hover Event In WebDriver Actions actions = new Actions(driver); WebElement moveonmenu = driver.findElement(By.xpath("//div[@id='menu1']/div")); actions.moveToElement(moveonmenu); actions.perform(); Above example will move mouse on targeted element. VIEW PRACTICAL EXAMPLE OF MOUSE HOVER. 17. Handling Multiple Windows In Selenium WebDriver. 1. Get All Window Handles. Set AllWindowHandles = driver.getWindowHandles(); 2. Extract parent and child window handle from all window handles. String window1 = (String) AllWindowHandles.toArray()[0]; String window2 = (String) AllWindowHandles.toArray()[1]; 3. Use window handle to switch from one window to other window. driver.switchTo().window(window2); Above given steps with helps you to get window handle and then how to switch from one window to another window. VIEW PRACTICAL EXAMPLE OF HANDLING MULTIPLE WINDOWS IN WEBDRIVER 18. Check Whether Element is Enabled Or Disabled In Selenium Web driver. boolean fname = driver.findElement(By.xpath("//input[@name='fname']")).isEnabled(); System.out.print(fname); Above syntax will verify that element (text box) fname is enabled or not. You can use it for any input element. VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT IS ENABLED OR NOT. 19. Enable/Disable Textbox During Selenium Webdriver Test Case Execution. JavascriptExecutor javascript = (JavascriptExecutor) driver; String todisable = "document.getElementsByName('fname') [0].setAttribute('disabled', '');"; javascript.executeScript(todisable); String toenable = "document.getElementsByName('lname') [0].removeAttribute('disabled');";
javascript.executeScript(toenable); It will disable fname element using setAttribute() method and enable lname element using removeAttribute() method. VIEW PRACTICAL EXAMPLE OF ENABLE/DISABLE TEXTBOX. 20. Selenium WebDriver Assertions With TestNG Framework
assertEquals
Assert.assertEquals(actual, expected); assertEquals assertion helps you to assert actual and expected equal values. VIEW PRACTICAL EXAMPLE OF assertEquals ASSERTION
assertNotEquals
Assert.assertNotEquals(actual, expected); assertNotEquals assertion is useful to assert not equal values. VIEW PRACTICAL EXAMPLE OF assertNotEquals ASSERTION.
assertTrue
Assert.assertTrue(condition); assertTrue assertion works for boolean value true assertion. VIEW PRACTICAL EXAMPLE OF assertTrue ASSERTION.
assertFalse
Assert.assertFalse(condition); assertFalse assertion works for boolean value false assertion. VIEW PRACTICAL EXAMPLE OF assertFalse ASSERTION. 21. Submit() method to submit form driver.findElement(By.xpath("//input[@name='Company']")).submit(); It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT FORM. 22. Handling Alert, Confirmation and Prompts Popups String myalert = driver.switchTo().alert().getText(); To store alert text. VIEW PRACTICAL EXAMPLE OF STORE ALERT TEXT driver.switchTo().alert().accept(); To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT driver.switchTo().alert().dismiss();
To dismiss confirmation. VIEW PRACTICAL EXAMPLE OF CANCEL CONFIRMATION driver.switchTo().alert().sendKeys("This Is John"); To type text In text box of prompt popup. elenium WebDriver : Handling Javascript Alerts, Confirmations And Prompts Alerts, Confirmation and Prompts are very commonly used elements of any webpage and you must know how to handle all these popups In selenium webdriver. If you know, Selenium IDE has many commands to handle alerts, confirmations and prompt popups like assertAlert, assertConfirmation, storeAlert, verifyAlertPresent, etc.. First of all, Let me show you all three different popup types to remove confusion from your mind and then we will see how to handle them In selenium webdriver. Alert Popup Generally alert message popup display with alert text and Ok button as shown In bellow given Image.
Confirmation Popup Confirmation popup displays with confirmation text, Ok and Cancel button as shown In bellow given Image.
Prompt Popup Prompts will have prompt text, Input text box, Ok and Cancel buttons.
Selenium webdriver has Its own Alert Interface to handle all above different popups. Alert Interface has different methods like accept(), dismiss(), getText(), sendKeys(java.lang.String keysToSend) and we can use all these methods to perform different actions on popups. VIEW WEBDRIVER EXAMPLES STEP BY STEP Look at the bellow given simple example of handling alerts, confirmations and prompts In selenium webdriver. Bellow given example will perform different actions (Like click on Ok button, Click on cancel button, retrieve alert text, type text In prompt text box etc..)on all three kind of popups using different methods od Alert Interface. Run bellow given example In eclipse with testng and observe the result. package Testng_Pack; import java.util.concurrent.TimeUnit; import import import import import import import
org.openqa.selenium.Alert; org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver; org.testng.annotations.AfterTest; org.testng.annotations.BeforeTest; org.testng.annotations.Test;
public class unexpected_alert { WebDriver driver; @BeforeTest public void setup() throws Exception { driver =new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html"); } @AfterTest
public void tearDown() throws Exception { driver.quit(); } @Test public void Text() throws InterruptedException { //Alert Pop up Handling. driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click(); //To locate alert. Alert A1 = driver.switchTo().alert(); //To read the text from alert popup. String Alert1 = A1.getText(); System.out.println(Alert1); Thread.sleep(2000); //To accept/Click Ok on alert popup. A1.accept(); //Confirmation Pop up Handling. driver.findElement(By.xpath("//button[@onclick='myFunction()']")).click(); Alert A2 = driver.switchTo().alert(); String Alert2 = A2.getText(); System.out.println(Alert2); Thread.sleep(2000); //To click On cancel button of confirmation box. A2.dismiss(); //Prompt Pop up Handling. driver.findElement(By.xpath("//button[contains(.,'Show Me Prompt')]")).click(); Alert A3 = driver.switchTo().alert(); String Alert3 = A3.getText(); System.out.println(Alert3); //To type text In text box of prompt pop up. A3.sendKeys("This Is John"); Thread.sleep(2000); A3.accept(); } } This way you can handle different kind of alerts very easily using Alert Interface of selenium webdriver. NEXT POST will show you how to handle unexpected alerts In selenium webdriver. How To Handle Unexpected Alerts In Selenium WebDriver Some times when we browsing software web application, Display some unexpected alerts due to some error or some other reasons. This kind of alerts not display every time but they are displaying only some time. If
you have created webdriver test case for such page and not handled this kind of alerts In your code then your script will fail Immediately If such unexpected alert pop up displayed. We have already learnt, How to handle expected alert popups In selenium webdriver In THIS EXAMPLE. Now unexpected alert appears only some times so we can not write direct code to accept or dismiss that alert. In this kind of situation, we have to handle them specially. You can VIEW ALL WEBDRIVER TUTORIALS ONE BY ONE. To handle this kind of unexpected alerts, You must at least aware about on which action such unexpected alert Is generated. Sometimes, They are generated during page load and sometime they are generated when you perform some action. So first of all we have to note down the action where such unexpected alert Is generated and then we can check for alert after performing that action. We need to use try catch block for checking such unexpected alters because If we will use direct code(without try catch) to accept or dismiss alert and If alert not appears then our test case will fail. try catch can handle both situations. I have one example where alert Is displaying when loading page. So we can check for alert Inside try catch block after page load as shown In bellow given example. After loading page, It will check for alert. If alert Is there on the page then It will dismiss It else It will go to catch block and print message as shown In bellow given example. Run bellow given example In eclipse with testng and observe the result. package Testng_Pack; import java.util.concurrent.TimeUnit; import import import import import import
org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.firefox.FirefoxDriver; org.testng.annotations.AfterTest; org.testng.annotations.BeforeTest; org.testng.annotations.Test;
public class unexpected_alert { WebDriver driver; @BeforeTest public void setup() throws Exception { driver =new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");
} @AfterTest public void tearDown() throws Exception { driver.quit(); } @Test public void Text() throws InterruptedException { //To handle unexpected alert on page load. try{ driver.switchTo().alert().dismiss(); }catch(Exception e){ System.out.println("unexpected alert not present"); } driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname "); driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname "); driver.findElement(By.xpath("//input[@type='submit']")).click(); } } Above given webdriver code Is just for example. It Is just explaining the way of using try catch block to handle unexpected alert. You can use such try catch block In that area where you are facing unexpected alerts very frequently. * Open Firefox Browser Locating Web Element By ClassName In Selenium WebDriver with example There are many different ways of locating elements in webdriver for your software web application page and I have described one of them in my PREVIOUS POST with example. In webdriver, we can't do any thing on web page if you don't know how to locate an element. As you know, we can use element's ID to locate that specific element but suppose if your element do not have any ID then how will you locate that element ? Locating web element by className is good alternative if your element contains class name. We can locate element By Tag Name, By Name, By Link Text, By Partial Link Text, By CSS and By XPATH too but will look about them in my next posts. How to get the class name of element You can get the class name of element using firebug as shown in bellow given image.
Look in to above image. Post date content has a class and we can use that class name to store that blog post date string. Notice one more thing in above image, blog post date string has not any ID so we can not locate it by ID. (Note : You can view more webdriver tutorials on THIS LINK.) Example Of Locating Web Element By ClassName We can use bellow given syntax to locate that element. driver.findElement(By.className("date-header")); Practical example of locating web element by className is as bellow. package junitreportpackage; import java.util.concurrent.TimeUnit; import import import import import import import
org.junit.After; org.junit.Before; org.junit.Test; org.openqa.selenium.By; org.openqa.selenium.WebDriver; org.openqa.selenium.WebElement; org.openqa.selenium.firefox.FirefoxDriver;
public class Mytest1 { //To open Firefox browser WebDriver driver = new FirefoxDriver(); @Before public void beforetest() { //To Maximize Browser Window driver.manage().window().maximize(); //To Open URL In browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html"); } @After public void aftertest() { driver.quit(); } @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); String datentime = driver.findElement(By.className("dateheader")).getText();//Locating element by className and store its text to variable datentime. System.out.print(datentime); } } In above example, WebDriver driver = new FirefoxDriver() will open webdriver's Firefox browser instance. VIEW THIS POST TO KNOW HOW TO RUN WEBDRIVER TEST IN GOOGLE CHROME. driver.get(); will open targeted URL in browser. How To Locate Elements By ID In Selenium WebDriver With Example Before using WebDriver, You must be aware about different ways of locating an elements in WebDriver. Locating an element is essential part in selenium WebDriver because when you wants to take some action on element (typing text or clicking on button), first you need to locate that specific element to perform action. First of all I recommend you to read all these selenium IDE element locating methods and then read this article about Selenium WebDriver element locators to get all locating methods in better way. WebDriver which is also known as a Selenium 2 has many different ways of locating element. Let me explain each of them with examples. Here I am explaining how to locate element By id and will describe Locating Web Element By ClassName in my Next Post and others in latter posts. Locating UI Element By ID If your webpage element has unique and static ID then you can locate your page element by ID. Look in to bellow given image. You can verify that your webelement has any id or not using the firebug.
In above image, Submit Query button has unique id = 'submitButton'. I can use that id to locate button as bellow. driver.findElement(By.id("submitButton")); Bellow given example will show you how to locate element by id and then how to click on it. Copy bellow given @Test method part and replace it with the @Test method part of example given on this page.(Note : @Test method is marked with pink color in that example). @Test public void test() { driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); for (int i = 0; i<=20; i++) { WebElement btn = driver.findElement(By.id("submitButton"));//Locating element by id if (btn.isEnabled()) { //if webelement's attribute found enabled then this code will be executed. System.out.print("\nCongr8s... Button is enabled and webdriver is clicking on it now"); //Locating button by id and then clicking on it. driver.findElement(By.id("submitButton")).click(); i=20; } else { //if webelement's attribute found disabled then this code will be executed. System.out.print("\nSorry but Button is disabled right now..");
} try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } * Submitting Form Using .submit() Method Submitting Form Using submit() Method Of Selenium WebDriver You will find many forms In any website like Contact Us form, New User Registration Form, Inquiry Form, LogIn Form etc.. Supposing you are testing one site where you have to prepare Login form submission test case In selenium webdriver then how will you do It? Simplest way Is described In THIS POST. If you will see In that example post, we have used .click() method to click on Login button. 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. WEBDRIVER TUTORIAL PART 2 When to use .click() method You can use .click() method to click on any button. Means element's type = "button" or type = "submit", .click() method will works for both. When to use .submit() method If you will look at firebug view for any form's submit button then always It's type will be "submit" as shown In bellow given Image. In this case, .submit() method Is very good alternative of .click() method.
Final Notes : 1. If any form has submit button which has type = "button" then .submit() method will not work. 2. If button Is not Inside