Thursday, February 25, 2016

Java Basics : Constructors



                           Java Basics : Constructors



A constructor is a special method that is used to initialize an object.Every class has a constructor,if we don't explicitly declare a constructor for any java class the compiler builds a default constructor for that class. A constructor does not have any return type.
A constructor has same name as the class in which it resides. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.
class Car
{
 String name ;
 String model;
 Car( )    //Constructor 
 {
  name ="";
  model="";
 }
}  

There are two types of Constructor

  • Default Constructor
  • Parameterized constructor
Each time a new object is created at least one constructor will be invoked.
Car c = new Car()       //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked

Constructor Overloading

Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters. Constructor overloading is not much different than method overloading. In case of method overloading you have multiple methods with same name but different signature, whereas in Constructor overloading you have multiple constructor with different signature but only difference is that Constructor doesn't have return type in Java.

Q. Why do we Overload constructors ?

Constructor overloading is done to construct object in different ways.

Example of constructor overloading

class Cricketer 
{
 String name;
 String team;
 int age;
 Cricketer ()   //default constructor.
 {
  name ="";
  team ="";
  age = 0;
 }
 Cricketer(String n, String t, int a)   //constructor overloaded
 {
  name = n;
  team = t;
  age = a;
 }
 Cricketer (Cricketer ckt)     //constructor similar to copy constructor of c++ 
 {
  name = ckt.name;
  team = ckt.team;
  age = ckt.age;
 }
 public String toString() 
 {
  return "this is " + name + " of "+team;
 }
}

Class test:
{
 public static void main (String[] args)
 {
  Cricketer c1 = new Cricketer();
  Cricketer c2 = new Cricketer("sachin", "India", 32);
  Cricketer c3 = new Cricketer(c2 );
  System.out.println(c2);
  System.out.println(c3);
  c1.name = "Virat";
  c1.team= "India";
  c1.age = 32;
  System .out. print in (c1);
 }
}
output:
this is sachin of india
this is sachin of india
this is virat of india


Frequently asked questions 

1. Define Constructor?

  • Constructor is a special method given in OOP language for creating and initializing object.
  • In java , constructor role is only initializing object , and new keyword role is creating object.

2.What are the Rules in defining a constructor?

  •  Constructor name should be same as class name.
  • It should not contain return type.
  • It should not contain Non Access Modifiers: final ,static, abstract, synchronized
  • In it logic return statement with value is not allowed.
  • It can have all four accessibility modifiers: private , public, protected, default
  • It can have parameters
  • It can have throws clause: we can throw exception from constructor.
  • It can have logic, as part of logic it can have all java legal statement except return statement with value.
  • We can not place return in constructor.

 3. Can we define a method with same name of class?

  • Yes, it is allowed to define a method with same class name. No compile time error and no runtime error is raised, but it is not recommended as per coding standards.

4.If we place return type in constructor prototype will it leads to Error?

  • No, because compiler and JVM considers it as a method.

5. How compiler and JVM can differentiate constructor and method definitions of both have same class name?

  • By using return type , if there is a return type it is considered as a method else it is considered as constructor.

6. How compiler and JVM can differentiate constructor and method invocations of both have same class name?

  • By using new keyword, if new keyword is used in calling then constructor is executed else method is executed.

7.Why return type is not allowed for constructor?

  •  As there is a possibility to define a method with same class name , return type is not allowed to constructor to differentiate constructor block from method block.

8.Why constructor name is same as class name?

  •  Every class object is created using the same new keyword , so it must have information about the class to which it must create object .
  • For this reason constructor name should be same as class name.

9.Can we declare constructor as private?

  •  Yes we can declare constructor as private.
  • All four access modifiers are allowed to
  •  constructor.
  • We should declare constructor as private for not to allow user to create object from outside of our class.
  • Basically we will declare private constructor in Singleton design pattern.

10.Is Constructor definition is mandatory in class?

  •  No, it is optional . If we do not define a constructor compiler will define a default constructor.

11. Why compiler given constructor is called as default constructor?

  • Because it obtain all its default properties from its class.
  • They are
    1.Its accessibility modifier is same as its class accessibility modifier 
    2.Its name is same as class name.
    3.Its does not have parameters and logic.

12. what is default accessibility modifier of default constructor?

  •  It is assigned from its class.

13.When compiler provides default constructor?

  •  Only if there is no explicit constructor defined by developer.

14.When developer must provide constructor explicitly?

  • If we want do execute some logic at the time of object creation, that logic may be object initialization logic or some other useful logic.

15.If class has explicit constructor , will it have default constructor?

  • No. compiler places default constructor only if there is no explicit constructor.

16.Can abstract class have constructor ?

  • Yes, abstract can have constructor for chaining for constructor .when any class extend abstract class, constructor of sub class will invoke constructor of super class either implicitly or explicitly. 

Wednesday, February 24, 2016

Java Basics : Comparable vs Comparator

Java Basics : Comparable vs Comparator


Difference

Comparable lets a class implement its own comparison:
  • it's in the same class (it is often an advantage)
  • there can be only one implementation (so you can't use that if you want two different cases)
  • A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
  • Comparable provides compareTo() method to sort elements.
  • Comparable is found in java.lang package
  • We can sort the list elements of Comparable type byCollections.sort(List) method.
By comparison, Comparator is an external comparison:
  • it is typically in a unique instance (either in the same class or in another place)
  • you name each implementation with the way you want to sort things
  • you can provide comparators for classes that you do not control
  • the implementation is usable even if the first object is null
  • A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface
  • Comparator provides compare() method to sort elements
  • Comparator is found in java.util package.
  • We can sort the list elements of Comparator type byCollections.sort(List,Comparator) method.

Comparable Example

The Employee class where we are implementing Comparable
===========================================
public class Employee implements Comparable<Employee> {

String empName;
int empId;

public Employee(String empName, int empId )
{ super();
this.empId=empId;
this.empName=empName;
}
@Override
public int compareTo(Employee emp) {
return (this.empId<emp.empId)?-1 :(this.empId>emp.empId)?1:0;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

}
=================================
The main Class
=================================
import java.util.*;

public class EmployeeComparableMain {

public static void main(String[] args) {
Employee e1= new Employee("Steve",1);
Employee e2= new Employee("Jack",2);
Employee e3= new Employee("Ram",5);
Employee e4= new Employee("Lova",3);


List<Employee> list = new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);

Iterator itr=list.iterator();
while(itr.hasNext())
{
Employee emp=  (Employee) (itr.next());
System.out.println("Name :" +emp.getEmpName()+"  Id=" +emp.empId );
}

Collections.sort(list);

itr=list.iterator();
while(itr.hasNext())
{
Employee emp=  (Employee) (itr.next());
System.out.println("Name :" +emp.getEmpName()+"  Id=" +emp.empId );
}

Collections.sort(list);
}

}
============
o/P
============
Name :Steve  Id=1
Name :Jack  Id=2
Name :Ram  Id=5
Name :Lova  Id=3
Name :Steve  Id=1
Name :Jack  Id=2
Name :Lova  Id=3
Name :Ram  Id=5

=================================================

For Comparator

We will create class country having attribute id and name and will create another classCountrySortByIdComparator which will implement Comparator interface and implement a compare method to sort collection of country object by id and we will also see how to use anonymous comparator.

1.Country.java 

public class Country{
    int countryId;
    String countryName;
    
    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }

    public int getCountryId() {
        return countryId;
    }


    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }


    public String getCountryName() {
        return countryName;
    }


    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    
} 

2.CountrySortbyIdComparator.java

package org.arpit.javapostsforlearning;

import java.util.Comparator;
//If country1.getCountryId()<country2.getCountryId():then compare method will return -1
//If country1.getCountryId()>country2.getCountryId():then compare method will return 1
//If country1.getCountryId()==country2.getCountryId():then compare method will return 0
 public class CountrySortByIdComparator implements Comparator<Country>{

    @Override
    public int compare(Country country1, Country country2) {
        
        return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
    }

}

3.ComparatorMain.java

package org.arpit.javapostsforlearning;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
   Country indiaCountry=new Country(1, "India");
   Country chinaCountry=new Country(4, "China");
   Country nepalCountry=new Country(3, "Nepal");
   Country bhutanCountry=new Country(2, "Bhutan");
   
         List<Country> listOfCountries = new ArrayList<Country>();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(chinaCountry);
         listOfCountries.add(nepalCountry);
         listOfCountries.add(bhutanCountry);
  
         System.out.println("Before Sort by id : ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"||"+"Country name: "+country.getCountryName());
   }
         Collections.sort(listOfCountries,new CountrySortByIdComparator());
         
         System.out.println("After Sort by id: ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
   }
         
         //Sort by countryName
         Collections.sort(listOfCountries,new Comparator<Country>() {

    @Override
    public int compare(Country o1, Country o2) {
     return o1.getCountryName().compareTo(o2.getCountryName());
    }
   });
   
   System.out.println("After Sort by name: ");
         for (int i = 0; i < listOfCountries.size(); i++) {
    Country country=(Country) listOfCountries.get(i);
    System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
   }
 }

}

Output:

Before Sort by id : 
Country Id: 1||Country name: India
Country Id: 4||Country name: China
Country Id: 3||Country name: Nepal
Country Id: 2||Country name: Bhutan
After Sort by id: 
Country Id: 1|| Country name: India
Country Id: 2|| Country name: Bhutan
Country Id: 3|| Country name: Nepal
Country Id: 4|| Country name: China
After Sort by name: 
Country Id: 2|| Country name: Bhutan
Country Id: 4|| Country name: China
Country Id: 1|| Country name: India
Country Id: 3|| Country name: Nepal

Tuesday, February 9, 2016

SQL Interview Questions for Tester / QA

Q#1. What is a primary Key?
Ans. Primary key : Each row of the data in a table uniquely identified by a Primary Key The column  (columns) that has completely unique data throughout the table is known as the primary key field

 primary key, also called a primary keyword, is a key in a relational database that is unique for each record. It is a unique identifier, such as a driver license number, telephone number (including area code), or vehicle identification number (VIN). A relational database must always have one and only one primary key. Primary keys typically appear as columns in relational database tables.

Q#2. How to select all records from the table?
Ans. To select all the records from the table we need to use following syntax:

Select * from table_name;

Q#3. Define join and name different type of joins?
Ans. Join keyword is used to fetch data from related two or more tables. It returns rows where there is at least one match in both the tables included in join. Read more here.
Type of joins are-

Right Join
Outer Join
Full Join
Cross Join
Self Join.

Q#4. What is the syntax to add record to a table?
Ans. To add record in a table INSERT syntax is used.

Ex: INSERT into table_name VALUES (value1, value2..);

Q#5. How do you add a column to a table?
Ans. To add another column in the table following command has been used.

ALTER TABLE table_name ADD (column_name);

Q#6. Define SQL Delete statement.
Ans. Delete is used to delete a row or rows from a table based on the specified condition.
Basic syntax is as follows:

DELETE FROM table_name

WHERE <Condition>

Q#7. Define COMMIT ?
Ans. COMMIT saves all changes made by DML statements.

Q#8. What is a primary key?
Ans. A Primary key is column whose values uniquely identify every row in a table. Primary key values can never be reused.

Q#9. What are foreign keys?
Ans. When a one table’s primary key field is added to related tables in order to create the common field which relates the two tables, it called a foreign key in other tables.
Foreign Key constraints enforce referential integrity.

Q#10. What is CHECK Constraint?
Ans. A CHECK constraint is used to limit the values or type of data that can be stored in a column. They are used to enforce domain integrity.

Q#11. Is it possible for a table to have more than one foreign key?
Ans. Yes, a table can have many foreign keys and only one primary key.

Q#12. What are the possible values for BOOLEAN data field.
Ans. For a BOOLEAN data field two values are possible: -1(true) and 0(false).

Q#13. What is a stored procedure?
Ans. A stored procedure is a set of SQL queries which can take input and send back output.

Q#14. What is identity in SQL?
Ans. An identity column in the SQL automatically generates numeric values. We can defined a start and increment value of identity column.

Q#15. What is Normalization?
Ans. The process of table design to minimize the data redundancy is called normalization. We need to divide a database into two or more table and define relationships between them.

Benefits :

  1. Eliminate data redundancy
  2. Improve performance
  3. Query optimization
  4. Faster update due to less number of columns in one table
  5. Index improvement

Q#16. What is Trigger?
Ans. Trigger allows us to execute a batch of SQL code when a table event occurs (Insert, update or delete command executed against a specific table)

Q#17. How to select random rows from a table?
Ans. Using SAMPLE clause we can select random rows.

Example:
SELECT * FROM table_name SAMPLE(10);

Q#18. Which TCP/IP port does SQL Server run?
Ans. By default SQL Server runs on port 1433.

Q#19. Write a SQL SELECT query that only returns each name only once from a table?
Ans. To get the each name only once, we need to use the DISTINCT keyword.

SELECT DISTINCT name FROM table_name;

Q#20. Explain DML and DDL?
Ans. DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE  are DML statements.

DDL stands for Data Definition Language. CREATE ,ALTER, DROP, RENAME are DDL statements.

Q#21. Can we rename a column in the output of SQL query?
Ans. Yes using the following syntax we can do this.

SELECT column_name AS new_name FROM table_name;

Q#22. Give the order of SQL SELECT ?
Ans. Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. Only the SELECT and FROM clause are mandatory.

Q#23. Suppose a Student column has two columns, Name and Marks. How to get name and marks of top three students.
Ans. SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT(*) FROM Students s2 WHERE s1.marks = s2.marks)

Q#24. What is SQL comments?
Ans. SQL comments can be put by two consecutive hyphens (–).

Q#25. Difference between TRUNCATE, DELETE and DROP commands?
Ans. DELETE removes some or all rows from a table based on the condition. It can be rolled back.

TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The operation cannot be rolled back

DROP command removes a table from the database completely.

Q#26. What are the properties of a transaction?
Ans. Generally these properties are referred as ACID properties. They are:

Atomicity
Consistency
Isolation
Durability.
Q#27. What do you mean by ROWID ?
Ans. It’s a 18 character long pseudo column attached with each row of a table.

Q#28. Define UNION, MINUS, UNION ALL, INTERSECT ?
Ans. MINUS – returns all distinct rows selected by the first query but not by the second.

UNION – returns all distinct rows selected by either query

UNION ALL – returns all rows selected by either query, including all duplicates.

INTERSECT – returns all distinct rows selected by both queries.

Q#29. What is a transaction?
Ans. A transaction is a sequence of code that runs against a database. It takes database from one consistent state to another.

------------
Q#30. What is difference between UNIQUE and PRIMARY KEY constraints?
Ans. A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys.

Primary key cannot contain Null values whereas Unique key can contain Null values.

Q#31. What is a composite primary key?
Ans. Primary key created on more than one column is called composite primary key.

Q#32. What is an Index ?
Ans. An Index is an special structure associated with a table speed up the performance of queries. Index can be created on one or more columns of a table.

Q#33. What is the Subquery ?
Ans. A Subquery is sub set of select statements whose return values are used in filtering conditions of the main query.

Q#34. What do you mean by query optimization?
Ans. Query optimization is a process in which database system compares different query strategies and select the query with the least cost.

Q#35. What is Collation?
Ans. Set of rules that defines how data is stored, how case sensitivity and Kana character can be treated etc.

Q#36. What is Referential Integrity?
Ans. Set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

Q#37. What is Case Function?
Ans. Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions and returns one of multiple possible result expressions.

Q#38. Define a temp table?
Ans. A temp table is a temporary storage structure to store the data temporarily.

Q#39. How we can avoid duplicating records in a query?
Ans. By using DISTINCT keyword duplicating records in a query can be avoided.

Q#40. Explain the difference between Rename and Alias?
Ans. Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column.

Q#41. What is a View?
Ans. A view is a virtual table which contains data from one or more tables. Views restrict data access of table by selecting only required values and make complex queries easy.

Q#42. What are the advantages of Views?
Ans. Advantages of Views:

Views restrict access to the data because the view can display selective columns from the table.
Views can be used to make simple queries to retrieve the results of complicated queries. For example, views can be used to query information from multiple tables without the user knowing.
Q#43. List the various privileges that a user can grant to another user?
Ans.   SELECT, CONNECT, RESOURCES.

Q#44. What is schema?
Ans. A schema is collection of database objects of a User.

Q#45. What is Table ?
Ans. A table is the basic unit of data storage in the database management system. Table data is stored in rows and columns.

Q#46. Do View contain Data?
Ans. No, Views are virtual structure.

Q#47. Can a View based on another View?
Ans. Yes, A View is based on another View.

Q#48. What is difference between Having clause and Where clause?
Ans. Both specify a search condition but Having clause is used only with the SELECT statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaves like WHERE clause only.

Q#49. What is difference between Local and Global temporary table?
Ans. If defined in inside a compound statement a local temporary table exists only for the duration of that statement but a global temporary table exists permanently in the db but its rows disappears when the connection is closed.

Q#50. What is CTE?
Ans. A CTE or common table expression is an expression which contains temporary result set which is defined in a SQL statement.

Thursday, February 4, 2016

TestNG Basics

TestNG Basics


TestNG is a testing framework developed in the lines of JUnit and NUnit, however it introduces some new functionalities that make it more powerful and easier to use.
TestNG is designed to cover all categories of tests − unit, functional, end-to-end, integration, etc., and it requires JDK 5 or higher.
This tutorial provides a good understanding on TestNG framework needed to test an enterprise level application to deliver it with robustness and reliability.

Features of TestNG
  • Support for annotations
  • Support for parameterization
  • Advance execution methodology that do not require test suites to be created
  • Support for Data Driven Testing using Dataproviders
  • Enables user to set execution priorities for the test methods
  • Supports threat safe environment when executing multiple threads
  • Readily supports integration with various tools and plug-ins like build tools (Ant, Maven etc.), Integrated Development Environment (Eclipse).
  • Facilitates user with effective means of Report Generation using ReportNG
TestNG versus JUnit
There are various advantages that make TestNG superior to JUnit. Some of them are:
  • Parameters & dataproviders
  • Advance and easy annotations
  • Execution patterns can be set
  • Concurrent execution of test scripts
  • Test case dependencies can be set
Annotations are preceded by a “@” symbol in both TestNG and JUnit.
So now let us get started with the installation and implementation part.

TestNG Installation in Eclipse

Follow the below steps to TestNG Download and installation on eclipse:
Step 1Launch eclipse IDE -> Click on the Help option within the menu -> Select “Eclipse Marketplace..” option within the dropdown.
Selenium TestNG tutorial 1
Step 2: Enter the keyword “TestNG” in the search textbox and click on “Go” button as shown below.
Selenium TestNG tutorial 2
Step 3: As soon as the user clicks on the “Go” button, the results matching to the search string would be displayed. Now user can click on the Install button to install TestNG.
Selenium TestNG tutorial 3
Step 4: As soon as the user clicks on the Install button, the user is prompted with a window to confirm the installation. Click on “Confirm” button.
Selenium TestNG tutorial 4
Step 5: In the next step, the application would prompt you to accept the license and then click on the “Finish” button.
Step 6: The installation is initiated now and the progress can be seen as following:
Selenium TestNG tutorial 5
We are advised to restart our eclipse so as to reflect the changes made.
Upon restart, user can verify the TestNG installation by navigating to “Preferences” from “Window” option in the menu bar. Refer the following figure for the same.
Selenium TestNG tutorial 6
(Click on image to view enlarged)
Selenium TestNG tutorial 7

Creation of Sample TestNG project

Let us begin with the creation of TestNG project in eclipse IDE.
Step 1: Click on the File option within the menu -> Click on New -> Select Java Project.
Selenium TestNG tutorial 8
Step 2: Enter the project name as “DemoTestNG” and click on “Next” button. As a concluding step, click on the “Finish” button and your Java project is ready.
Selenium TestNG tutorial 9
Step 3: The next step is to configure the TestNG library into the newly created Java project. For the same, Click on the “Libraries” tab under Configure Build Path. Click on “Add library” as shown below.
Selenium TestNG tutorial 10
Step 4: The user would be subjected with a dialog box promoting him/her to select the library to be configured. Select TestNG and click on the “Next” button as shown below in the image. In the end, click on the “Finish” button.
Selenium TestNG tutorial 11
The TestNG is now added to the Java project and the required libraries can be seen in the package explorer upon expanding the project.
Selenium TestNG tutorial 12
Add all the downloaded Selenium libraries and jars in the project’s build path as illustrated in the previous tutorial.

Creating TestNG class

Now that we have done all the basic setup to get started with the test script creation using TestNG. Let’s create a sample script using TestNG.
Step 1: Expand the “DemoTestNG” project and traverse to “src” folder. Right click on the “src”package and navigate to New -> Other..
Selenium TestNG tutorial 13
Step 2: Expand TestNG option and select “TestNG” class option and click on the “Next” button.
Selenium TestNG tutorial 14
Step 3: Furnish the required details as following. Specify the Source folder, package name and the TestNG class name and click on the Finish button. As it is evident from the below picture, user can also check various TestNG notations that would be reflected in the test class schema. TestNG annotations would be discussed later in this session.
Selenium TestNG tutorial 15
The above mentioned TestNG class would be created with the default schema.
Selenium TestNG tutorial 16
Now that we have created the basic foundation for the TestNG test script, let us now inject the actual test code. We are using the same code we used in the previous session.
Scenario:
  • Launch the browser and open “gmail.com”.
  • Verify the title of the page and print the verification result.
  • Enter the username and Password.
  • Click on the Sign in button.
  • Close the web browser.
Code:
------------
1package TestNG;
2import org.openqa.selenium.By;
3import org.openqa.selenium.WebDriver;
4import org.openqa.selenium.WebElement;
5import org.openqa.selenium.firefox.FirefoxDriver;
6import org.testng.Assert;
7import org.testng.annotations.Test;
8 
9public class DemoTestNG {
10       public WebDriver driver = new FirefoxDriver();
11       String appUrl = &quot;https://accounts.google.com&quot;;
12 
13@Test
14public void gmailLogin() {
15             // launch the firefox browser and open the application url
16              driver.get(&quot;https://gmail.com&quot;);
17              
18// maximize the browser window
19              driver.manage().window().maximize();
20              
21// declare and initialize the variable to store the expected title of the webpage.
22              String expectedTitle = &quot; Sign in - Google Accounts &quot;;
23              
24// fetch the title of the web page and save it into a string variable
25              String actualTitle = driver.getTitle();
26              Assert.assertEquals(expectedTitle,actualTitle);
27              
28// enter a valid username in the email textbox
29              WebElement username = driver.findElement(By.id(&quot;Email&quot;));
30              username.clear();
31              username.sendKeys(&quot;TestSelenium&quot;);
32 
33// enter a valid password in the password textbox
34              WebElement password = driver.findElement(By.id(&quot;Passwd&quot;));
35              password.clear();
36              password.sendKeys(&quot;password123&quot;);
37              
38// click on the Sign in button
39              WebElement SignInButton = driver.findElement(By.id(&quot;signIn&quot;));
40              SignInButton.click();
41              
42// close the web browser
43              driver.close();
44}
45}
Code Explanation with respect to TestNG
1) @Test – @Test is one of the TestNG annotations. This annotation lets the program execution to know that method annotated as @Test is a test method. To be able to use different TestNG annotations, we need to import the package “importorg.testng.annotations.*”.
2) There is no need of main() method while creating test scripts using TestNG. The program execution is done on the basis of annotations.
3) In a statement, we used Assert class while comparing expected and the actual value. Assert class is used to perform various verifications. To be able to use different assertions, we are required to import “import org.testng.Assert”.

Executing the TestNG script

The TestNG test script can be executed in the following way:
=> Right click anywhere inside the class within the editor or the java class within the package explorer, select “Run As” option and click on the “TestNG Test”.
Selenium TestNG tutorial 17
TestNG result is displayed into two windows:
  • Console Window
  • TestNG Result Window
Refer the below screencasts for the result windows:
Selenium TestNG tutorial 18
(Click on image to view enlarged)
Selenium TestNG tutorial 19

HTML Reports

TestNG comes with a great capability of generating user readable and comprehensible HTML reports for the test executions. These reports can be viewed in any of the browser and it can also be viewed using Eclipse’s build –in browser support.
To generate the HTML report, follow the below steps:
Step 1: Execute the newly created TestNG class. Refresh the project containing the TestNG class by right clicking on it and selecting “Refresh” option.
Step 2: A folder named as “test-output” shall be generated in the project at the “src” folder level. Expand the “test-output” folder and open on the “emailable-report.html” file with the Eclipse browser. The HTML file displays the result of the recent execution.
Selenium TestNG tutorial 20
Selenium TestNG tutorial 21
Step 3: The HTML report shall be opened with in the eclipse environment. Refer the below image for the same.
Selenium TestNG tutorial 22
Refresh the page to see the results for fresh executions if any.

Setting Priority in TestNG

Code Snippet
1package TestNG;
2import org.testng.annotations.*;
3public class SettingPriority {
4 
5@Test(priority=0)
6public void method1() {
7 }
8 
9@Test(priority=1)
10public void method2() {
11 }
12 
13@Test(priority=2)
14public void method3() {
15 }
16}

Code Walkthrough

If a test script is composed of more than one test method, the execution priority and sequence can be set using TestNG annotation “@Test” and by setting a value for the “priority” parameter.
In the above code snippet, all the methods are annotated with the help @Test and the priorities are set to 0, 1 and 2. Thus the order of execution in which the test methods would be executed is:
  • Method1
  • Method2
  • Method3
Support for Annotations
There are number of annotations provided in TestNG and JUnit. The subtle difference is that TestNG provides some more advance annotations to JUnit.

TestNG Annotations:

Following is the list of the most useful and favorable annotations in TestNG:
AnnotationDescription
@TestThe annotation notifies the system that the method annotated as @Test is a test method
@BeforeSuiteThe annotation notifies the system that the method annotated as @BeforeSuite must be executed before executing the tests in the entire suite
@AfterSuiteThe annotation notifies the system that the method annotated as @AfterSuite must be executed after executing the tests in the entire suite
@BeforeTestThe annotation notifies the system that the method annotated as @BeforeTest must be executed before executing any test method within the same test class
@AfterTestThe annotation notifies the system that the method annotated as @AfterTest must be executed after executing any test method within the same test class
@BeforeClassThe annotation notifies the system that the method annotated as @BeforeClass must be executed before executing the first test method within the same test class
@AfterClassThe annotation notifies the system that the method annotated as @AfterClass must be executed after executing the last test method within the same test class
@BeforeMethodThe annotation notifies the system that the method annotated as @BeforeMethod must be executed before executing any and every test method within the same test class
@AfterMethodThe annotation notifies the system that the method annotated as @AfterMethod must be executed after executing any and every test method within the same test class
@BeforeGroupsThe annotation notifies the system that the method annotated as @BeforeGroups is a configuration method that enlists a group and that must be executed before executing the first test method of the group
@AfterGroupsThe annotation notifies the system that the method annotated as @AfterGroups is a configuration method that enlists a group and that must be executed after executing the last test method of the group
Note: Many of the aforementioned annotations can be exercised in JUnit 3 and JUnit 4 framework also.

Conclusion

Through this tutorial, we tried to make you acquainted with a java based testing framework named as TestNG. We started off the session with the installation of the framework and moved with the script creation and advance topics. We discussed all the annotations provided by TestNG. We implemented and executed our first TestNG test script using annotations and assert statements.
Article summary:
  • TestNG is an advance framework designed in a way to leverage the benefits by both the developers and testers.
  • TestNG is an open source framework which is distributed under the Apache software License and is readily available for download.
  • TestNG is considered to be superior to JUnit because of its advance features.
  • Features of TestNG
    • Support for Annotations
    • Advance execution methodology that do not require test suites to be created
    • Support for parameterization
    • Support for Data Driven Testing using Dataproviders
    • Setting execution priorities for the test methods
    • Supports threat safe environment when executing multiple threads
    • Readily supports integration with various tools and plug-ins like build tools (Ant, Maven etc.), Integrated Development Environment (Eclipse).
    • Facilitates user with effective means of Report Generation using ReportNG
  • Advantages of TestNG over JUnit
    • Added advance and easy annotations
    • Execution patterns can be set
    • Concurrent execution of test scripts
    • Test case dependencies can be set
  • TestNG is freely available and can be easily installed in the Eclipse IDE using Eclipse Market.
  • Upon installation, TestNG would be available as a library within the Eclipse environment.
  • Create a new Java Project and configure the build path using TestNG library.
  • Create a new TestNG class by expanding the created TestNG project and traverse to its “src” folder. Right click on the “src” package and navigate to New -> Other. Select TestNG class option.
  • @Test is one of the annotations provided by TestNG. This annotation lets the program execution to know that method annotated as @Test is a test method. To be able to use different TestNG annotations, we need to import the package “import org.testng.annotations.*”.
  • There is no need of main() method while creating test scripts using TestNG.
  • We use Assert class while comparing expected and the actual value. Assert class is used to perform various verifications. To be able to use different assertions, we are required to import “import org.testng.Assert”.
  • If a test script is composed of more than one test methods, the execution priority and sequence can be set using TestNG annotation “@Test” and by setting a value for the “priority” parameter.
  • TestNG has a capability of generating human readable test execution reports automatically. These reports can be viewed in any of the browser and it can also be viewed using Eclipse’s built – in browser support.
===================================================

import org.testng.annotations.*;

public class TestNG {

@BeforeSuite
public void testBeforeSuite()
{
System.out.println(" Before Suite");
}
@BeforeTest
public void testBeforeTest()
{
System.out.println(" Before Test");
}
@BeforeGroups
public void testBeforeGroup()
{
System.out.println(" Before Groups");
}
@BeforeClass
public void testBeforeClass()
{
System.out.println(" Before Class");
}

@BeforeMethod
public void testBeforeMethod()
{
System.out.println(" Before Method");
}

@Test (groups= {"mats"})
public void testMethod()
{
System.out.println(" Test");
}
@AfterMethod
public void testAfterMethod()
{
System.out.println(" After Method");
}

@AfterClass
public void testAfterClass()
{
System.out.println(" After Class");
}
@AfterGroups
public void testAfterGroup()
{
System.out.println(" After Groups");
}
@AfterTest
public void testAfterTest()
{
System.out.println(" After Test");
}
@AfterSuite
public void testAfterSuite()
{
System.out.println(" After Suite");
}
}
========================
O/P

 Before Suite
 Before Test
 Before Class
 Before Method
 Test
 After Method
 After Class
 After Test
 After Suite
PASSED: testMethod

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================