What is difference between Selenium RC and Selenium WebDriver?

Selenium RC stands for Remote Control, if u use selenium RC libraries in your automation code you had to invoke a server with a specific port no. which would act as a medium between your automation code and application on browser.
But things became simpler with Selenium WebDriver. If you use selenium WebDriver libraries in your automation code you can invoke browsers directly from the automation code.
Selenium RC injects JavaScript function into browsers when the web page is loaded. Whereas Selenium WebDriver drives the browser using browser’s built-in support
The other differences are:

1. Web Driver has the ability to support HTML unit driver which can run the test in headless mode, however selenium RC needs a live browser to execute the test.
2. Web driver can be used for testing iPhone or Android apps. Selenium RC only supports web applications
3. Web driver cannot readily support new browsers since a driver code for new browser needs to be written to provide support. Selenium RC can easily support any browser.
4. Web driver has very good support and development community. Selenium RC has a limited support and dev community.
In WebDriver

  • Not necessary to start the server to run the programs
  • Web driver maintains the page load synchronization by default. If it is a page refresh we have to maintain by using thread.sleep ();
  • Web Driver is faster than Selenium RC because of its simpler architecture.
  • Web Driver directly talks to the browser while Selenium RC needs the help of the RC Server in order to do so.
  • Web Driver can support Html Unit while Selenium RC cannot.

How to use multiple browsers (firefox, Chrome, IE) from properties file ?

In my previous post, we talked about how can we use various browsers for testing using selenium WebDriver.

Refer below post:
Now. If you want to use multiple browsers and you want them to choose its value dynamically, let us suppose from properties file or from some xml file, we can do that.
So, you can set the browser value, suppose in properties file (at run time), then that particular browser should be invoked for testing.
First of all, you should know how to read properties file.
Please refer below post for learning How to read propertiesfile in selenium (java)?
Once you are able to read properties file, below lines of code will help you to select browser from properties file – 

package com.aayushCorp.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.ie.InternetExplorerDriver;



public class BrowserSelection {

public WebDriver selectBrowser() throws Exception {

FileInputStream fis = null;

File configfile = new File( "C:UsersPrakashworkspaceAayush-SeleniumsrccomaayushCorpexternalResourcesConfiguration.Properties");

fis = new FileInputStream(configfile);

Properties prop = new Properties();

prop.load(fis);

WebDriver driver = null;

String browser = prop.getProperty("browser");



while (browser == null) {

System.out.println("Browser is not specified in Configuration file. Terminating process !!!");

System.exit(0);

}

if (browser.equalsIgnoreCase("firefox")) {

driver = new FirefoxDriver();

System.out.println("Browser selected for testing is : Mozilla Firefox");

} else if (browser.equalsIgnoreCase("chrome")) {

System.setProperty("webdriver.chrome.driver", "C:chromedriver.exe");

driver = new ChromeDriver();

System.out.println("Browser selected for testing is : Google Chrome");



} else if (browser.equalsIgnoreCase("ie")) {

System.setProperty("webdriver.ie.driver", "C:IEDriverServer.exe");

driver = new InternetExplorerDriver();

System.out.println("Browser selected for testing is : Internet Explorer");



} else {

System.out.println("Selected browser value should be either firefox or chrome or ie --> Update in Configuration file is required");

System.exit(0);

}

return driver;

}

}

 In above peice of code, Selenium will launch either firefox or chrome or ie based on what value you specifies in properties file.

Hope this helps. Post your comments / suggestions.

Working with Mozilla Firefox, google chrome and Internet Explorer in Selenium WebDriver

We saw earlier that; Selenium WebDriver supports various programming languages and various web browsers for testing. Selenium WebDriver supports various browsers like IE, Firefox, Google Chrome, Opera. 
It can also be used on Android & iOS. Selenium WebDriver can support all operating systems where these browsers can run.
Suggested post to read: Introduction to Selenium 
Majorly people use Mozilla Firefox. In order to use Mozilla Firefox, we do not need to do any special configurations, but for using other browsers like Chrome and IE, we need to set system properties.
Let us talk one by one.
How to use Mozilla Firefox browser using selenium?
For using Mozilla Firefox in Selenium Webdriver, we do not need any configurations setup.
Just create a reference variable of the WebDriver instance and assign it to the instance of FiirefoxDriver class.
So, below line of code will launch Firefox web browser.

WebDriver driver = new FirefoxDriver();
Now, you can use “driver” instance for further process like navigating to URL and proceed with your testing.
To know more about Interface and to understand  Why do we write WebDriver driver = new FirefoxDriver() ?, refer below post
How to use Google Chrome browser using selenium?
In order to use Google Chrome for executing test cases, we need to set system property for “Webdriver.chrome.driver” with executable file of chrome driver (chromedriver.exe).
You can download chromedriver.exe file from here.
 
Once the chromedriver.exe file is downloaded, set system properties as –

      System.setProperty("webdriver.chrome.driver", "C:chromedriver.exe");
(assuming that it is stored at C drive, else provide your file location).
Now, once system property is set, we can launch chrome browser using below line of code – 
WebDriver driver = new ChromeDriver();
Now, you can use “driver” instance for further process like navigating to URL and proceed with your testing.
How to use Internet Explorer browser using selenium?
In order to use Internet Explorer for executing test cases, again, as like we did for google chrome, we need to set system property for “Webdriver.ie.driver” with executable file of IEDriverServer. (IEDriverServer.exe).
You can download IEDriverServer.exe file from here.
Once the IEDriverServer.exe file is downloaded, set system properties as –

   System.setProperty("webdriver.ie.driver", "C:IEDriverServer.exe");
 
(assuming that it is stored at C drive, else provide your file location).
Now, once system property is set, we can launch chrome browser using below line of code –
WebDriver driver = new InternetExplorerDriver();
Now, you can use “driver” instance for further process like navigating to URL and proceed with your testing.
Hope this helps. Drop your comments.

How to read properties file in selenium (java)?

Working with properties file in java / Selenium – 
Hard coding is not a good practice anywhere. It’s hard to go back and change something you’ve hard-coded previously in your code. Suppose you are testing some application. Consider that, its URL keep changing environment to environment, like in UT, UIT, ST, SIT, UAT etc.
Now, your application will be same but URL only will be different.
In this case if you are hard coding URL in your coding, then you need to update the URL whenever it changes.
 Same case would be with Username and password.
So, to overcome situations like this, we usually give these changing parameters in properties file.
You can create the properties file anywhere in the project, just make sure that you give correct path while loading the file.
I
n properties file each entry is stored as a pair of Strings, let us say, Name and value.
Now, let us see, how can we create properties file first of all.
Click on File -> New -> File
 Give some meaningful file name. save the file with “.properties” extension
Once the file is created, Open the file, and have some data, can refer below snap.
Now, the file is created. Let us see how to read this file in our program.
There are 3 simple steps to read file
1. Define FileInputStream & Give your file path of properties file. 

Ex –

File configfile = new File("C:UsersPrakashworkspaceAayush-SeleniumsrccomaayushCorpexternalResourcesConfiguration.Properties");

FileInputStream fis = new FileInputStream(configfile);

2. Load properties file 

For this, create object of properties file & then load.

Properties prop = new Properties();
prop.load(fis);

       3. Retrieve data from properties file.
Use below line to retrieve data.

     PropertyFileValue = prop.getProperty(key);
Below is the complete code, which return the value from properties file based on the key you supply.

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.Properties;

public class PropertyOperations {

public String getPropertyValueByKey(String key) {

String PropertyFileValue = null;

FileInputStream fis = null;

try {

File configfile = new File(
fis = new FileInputStream(configfile);

} catch (Exception e) {
System.out.println("Configuration file is not found. terminating Process !!!");

System.exit(0);

}

Properties prop = new Properties();

try {

prop.load(fis);

} catch (IOException e) {

e.printStackTrace();

}


Boolean isFileEmpty = prop.isEmpty();


if (isFileEmpty == false) {

PropertyFileValue = prop.getProperty(key);

} else {

System.out.println("Configuration file is empty. Processing is terminated");

System.exit(0);


}

return PropertyFileValue;


}

}

You can create object of this class in any class where you wanted to retrieve the data from properties file. And then retrieve the data by giving key.

Ex – 

PropertyOperations prop = new PropertyOperations();

String username = prop.getPropertyValueByKey("username")

Above piece of code will return username from properties file in to String username.

Post you questions in comment if you have any

 

Why do we write WebDriver driver = new FirefoxDriver(); ?

As we see, all the Selenium automation test scripts with a line –

WebDriver driver = new FirefoxDriver();
(depend on which browser do you use. To learn how can use other browsers like chrome and ie, refer below post.
Refer:  
 Working with Mozilla Firefox, google chrome and Internet Explorer in Selenium WebDriver (link))
Now, in above line, WebDriver is an interface. FirefoxDriver is a class. driver is instance. In other words, Instance of FirefoxDriver() (which is a class) is created and is stored in instance variable called “driver”.
To remember, An Interface contains empty methods that have been defined but not implemented.  These methods can be implemented by anyone.
FirefoxDriveris a class that has been written specifically for the Firefox browser. It has methods that are implemented and it can be instantiated. It can perform all functions (or methods) on the Firefox browser as defined in the interface WebDriver.

Above image best describes what we are reading in the post.
Do post your questions if you have any.

 

First Program in Selenium WebDriver to test www.google.com

Once we have configured Selenium jar files in to Eclipse (refer post: Downloading Selenium WebDriver Jars and configuring in eclipse), We are now good to start with Basic programs using Selenium.
We write the java program for selenium test in a java class. So, let us create one java class.
Right click on Package -> New -> Class (If you don’t find Class over there, then go to Other, and search for Java class there)
Give some meaningful name to the class and click on Finish.
The first basic thing is, we need to create driver of the web browser which will drive the flow.
Here I am using Mozilla Firefox driver.
Below is the sample code for my first selenium test where I am navigating to www.google.com and finding out the Title of the page.
Once the code is written in a class file, right click on it, select Run AS – > Java Application
Sample code – 

package basicsOfSelenium;


import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

public class FirstSeleniumTest {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();

driver.navigate().to("https://www.google.co.in");

String TitleOfPage = driver.getTitle();

System.out.println("Title of Current page is : "+TitleOfPage);

driver.close();
}

}

Sample Output:

Title of Current page is : Google
Good luck for your beginning

Do post your comments for any questions / suggestions.

How to Configure Log4j in your project (Using Log4j.xml file)?

 Configure Log4j in your project with the help of Log4j.xml file
To start with using logger, below steps explain, how can we use Log4j for logging the required messages which can be used later on, might be for debugging propose or is informative
Step1: Download Log4j from below link (Official site)
Log4j is a logging library used in java development. Firstly download Log4j.jar from its official site (Apache)
Step2: Add Log4j.jar to project library
We need to add this jar file in to the build path. To do this, right click on the project -> Build path -> Configure Build path -> Libraries tab -> Add external Jar -> Select Log4j.jar
Now Log4j is added in to your library and we are good use it.
Step3: Create Log4j.xml file (Note: Create Under src folder)
In order to configure Log4j in project, we need to specify various parameters in xml file.
The parameters we need to provide are logger, appenders, layout etc.
These parameters need to create in xml file.
To do this, right click on src folder -> New -> Other -> File -> give the name as “Log4j.xml”.
Now we can see the blank xml file.
Add the blow lines of code in to the xml file. Save the file.
(To learn about how logging can be achieved using log4j.properties file, click here– )
To write this xml file, one should know about 3 Main components of Log4j, different logging levels in Log4j.
Refer the blow links – 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration debug="true"

xmlns:log4j='http://jakarta.apache.org/log4j/'>



<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/>

</layout>

</appender>



<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">

<param name="append" value="false"/>

<param name="file" value="out/learning.log"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>

</layout>

</appender>



<root>

<level value="INFO"/>

<appender-ref ref="consoleAppender"/>

<appender-ref ref="fileAppender"/>

</root>



</log4j:configuration>

If you want to provide the max size, we can add below statement as param to RollingFileAppender.

<param name="maxFileSize" value="1MB" />
We can define ‘MaxBackupIndex’ option which determines the number of previously rolled files to preserve. MaxBackUp takes only a positive integer value. MaxBackUp value will be set to 1 by default. If we set it to zero, then no roll over occurs and the log file will be simply truncated when it reaches the MaxFileSize.

<param name="MaxBackupIndex" value="2"/>
Step4: Create Sample class where we will use Logger
Once Log4j.properties file is created, all is set to write log in your java program.
To achieve this, create sample class.
To define Logger class, use blow syntax
                        

Logger log = Logger.getLogger("your_class_name")
Import suitable respective jar.

Below sample code shows how can we log the information for various logging level.

Sample Program:

package com.aayushCorp.appData.tests;

import org.apache.log4j.Logger;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;


public class LoggerExampleTest {


public static void main(String[] args) {



Logger log = Logger.getLogger("LoggerExampleTest");

WebDriver driver = new FirefoxDriver();

driver.navigate().to("https://www.google.co.in");


log.info("This is Info message - Launched Google");

log.debug("This is debug message");

log.error("This is error message");

log.fatal("This is fatal mesage");

log.trace("This is trace message");



driver.close();

}


}

Run the program, you will see below output.

Output:

INFO [main] (LoggerExampleTest.java:16)- This is Info message - Launched Google

DEBUG [main] (LoggerExampleTest.java:17)- This is debug message

ERROR [main] (LoggerExampleTest.java:18)- This is error message

FATAL [main] (LoggerExampleTest.java:19)- This is fatal mesage

TRACE [main] (LoggerExampleTest.java:20)- This is trace message

Based on Log4j.xml file, log messages will be stored in .log file (text file) at the defined path on xml file.

Below screenshot shows the folder location and respective log file.
Hope this helps.
 Related Topic: 

What are the different logging levels in Log4j ?

There are several logging levels that you can configure in your application.
Anybody who is using logging in java must be familiar with basic java logging level e.g. DEBUG, INFO, WARN and ERROR.
Those are FATAL, ERROR, WARN, TRACE, DEBUG, INFO OR ALL in Apache logging. Default logging level is INFO.
Logging levels are given below:
1. ALL: All levels including custom levels also.
2. DEBUG: The DEBUG Level is used to indicate events that are useful to debug an application. Handling method for DEBUG level is: debug().
3. INFO: It gives the information about the progress of application and its states. General tips, news information etc.
4. WARN: It gives warning for unexpected events. The WARN level is used to indicate potentially harmful situations. Handling method for WARN level is: warn().
5. ERROR: It provides the information about error events. The ERROR level shows errors messages that might not be serious enough and allow the application to continue. Handling method for ERROR level is: error().
6. FATAL: It provides the information about application abort. The Fatal level is used to indicate severe events that will may cause abortion of the application. Handling method for FATAL level is: fatal().
7. OFF: It turns off all the logging. It is opposite to the ALL level. OFF java logging level has the highest possible rank and is intended to turn off logging in Java.
Standard order of all logging levels:
ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.
i.e. If logging level set to FATAL then only FATAL messages will be displayed, if logging level set to ERROR then ERROR and FATAL messages will be displayed and so on.
In the below example as we set the logging level to WARN so only WARN, ERROR and FATAL messages will be displayed. The DEBUG and INFO message will not display.
If you declare log level as debug in the configuration file, then all the other log messages will also be recorded.
If you declare log level as info in the configuration file, then info, warn, error and fatal log messages will be recorded.
If you declare log level as warn in the configuration file, then warn, error and fatal log messages will be recorded.
If you declare log level as error in the configuration file, then error and fatal log messages will be recorded.
If you declare log level as fatal in the configuration file, then only fatal log messages will be recorded.

How logging in Java affects performance?

Does Logging in java affects the performance of the application?    
    Logging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application’s runtime information.
    Logging does have its drawbacks also. It can slow down an application as it uses some CPU cycles and other resources (memory, etc). To answer these concerns, log4j is designed to be reliable, fast and extensible. Also, one should only log an error or something that must absolutely be logged. You can also log information helpful for debugging in the debug channel so it won’t affect production performance.
    Make sure you have a proper logging strategy. That means make sure you define what to log and have it separated into debug, trace, info, warning and error as well some others if you need them. Also make sure you give the ability to switch it on and off to enact performance/debugging as needed.
   Java logging severely affects performance of your application. Its quite common sense that more you log, more you perform file IO which slows down your application. That’s why choosing correct java logging level for every single message is quite important. Since having no java logging is not a choice you have to have logging in java application, what you can control is logging level and logging messages on that level. So always log DEBUG messages inside isDebugEnabled() block as shown in below example of debug mode in java.
 if(logger.isDebugEnabled()){
logger.debug("java logging level is DEBUG Enabled");
}

To improve performance:

>>  Change the ConversionPattern to use less expensive date/time formatting, and (more importantly) avoid ‘C’, ‘F’, ‘L’ and ‘M’ because they are particularly expensive.
>>   Change the logging Threshold to INFO or WARNING or ERROR to reduce the amount of logging,

>>   Put the Logger.debug(…) call inside an if statement that checks that debug logging is enabled. This   saves the cost of assembling the log message in cases where it won’t be needed;

>>  You can restrict junk logs like this. Set the root logger as INFO so that unnecessary debug logs won’t come and fill up your log file.
log4j.rootCategory=INFO, A1

>>   If you want specific class or package to give out DEBUG logs you can do it like this.

log4j.logger.org.hibernate.event.def.DefaultLoadEventListener=DEBUG,A1

The above will print DEBUG level logs from the class DefaultLoadEventListener in your log file along with other INFO level logs.

Main Components of Log4j

What are different appenders that can configure in log4j?
There are 3 main components that are used to log messages based upon type and level.
These components help to log messages according to message type and priority. Also provide the formatting option.
These components are:
– loggers
– appenders
– layouts
Logger Object is responsible for storing the information which need to be logged
We need to create Logger Object in a class (one per class).
Example:      static Logger log = Logger.getLogger(“your_class_name”);
Appender Objectis used to define the destination like file system, console, database, mail server etc. where user wants to save the log messages.
There are various appenders –
FileAppender –> used to write into a file. Files Appender is used to log the information into our custom name files. when we are configuring this appender, we can specify the file name
ConsoleAppender –> used to write into console. if we use this as appenders in your application, log4j logs the information in the console or command prompt window that is started with startup script.
JDBCAppender –> used to write in database
SMTPAppender –> used to send the log over mail
Again, in FileAppender we have 2 more
RollingFileAppenderwhich Rotates based on a maximum file size.
RollingFileAppender extends FileAppender to backup the log files when they reach a certain size. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender.
It has two important menthods –
setMaximumFileSize – Set the maximum size that the output file is allowed to reach before being rolled over to backup files.
setMaxBackupIndex – Set the maximum number of backup files to keep around.
DailyRollingFileAppender which Rotates based on dateFormat.
DailyRollingFileAppender extends FileAppender so that the underlying file is rolled over at a user chosen frequency. DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss.
Layout Object is responsible for layout and formating of the logging information to the desired format.
We have different type of layout classes in log4j
    SimpleLayout
    PatternLayout
    HTMLLayout
    XMLLayout