All selenium WebDriver jar files are available in the form of APIs.

What is API:

An application programming interface (API) is a computing interface that defines interactions between multiple software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc. It can also provide extension mechanisms so that users can extend existing functionality in various ways and to varying degrees. An API can be entirely custom, specific to a component, or it can be designed based on an industry-standard to ensure interoperability. Through information hiding, API s enable modular programming, which allows users to use the interface independently of the implementation.

How to use the APIs in selenium WebDriver:

You will find two approaches to use the APIs in the selenium WebDriver. First one,is to use the jar files and second is to call the dependency in your pom.xml page.

Below are the detailed steps to use the APIs in selenium WebDriver:

  1. Using jar files: This is the first approach.

Go to link https://mvnrepository.com/. Download the required jar files from here and add these jar files to your project. Below is a screenshot showing how to get the specified jar files for importing into your project.

Jar files

2. Adding dependency to your pom.xml: This is the second approach.

Step 01: Go to maven repository or click on the below link.

https://mvnrepository.com/artifact/org.apache.poi

Step 02: Search the necessary APIs which you want to use in your project.

Step 03: Once you get the required APIs just click on specific API.

Step 04: Click on the latest version of API.Copy the dependency which you can see and paste in your POM.xml page.

Frequently used APIs in selenium WebDriver:

Below is the list of APIs you can find in selenium WebDriver.

  1. Excel Reader utility -APACHE POI
  2. Log4J API
  3. JavaMail API
  4. JDBC API

1. Excel Reader utility -APACHE POI 4.1.0

This API is used to read, write, and perform different operations in the excel file.

To work with these APIs, you need to go to the maven repository (https://mvnrepository.com/) and download the specified jar files or copy the dependency and paste it into your maven project (inside the pom.xml).

Below is the utility for Excel Reader. Using this utility, you can perform excel operations, for example: read data, write data, counting rows and columns.

//Create your work book       

            public ExcelReader(String path) {

                        this.path=path;

                        try {

                                    fis = new FileInputStream(path);

                                    workbook = new XSSFWorkbook(fis);

                                    sheet = workbook.getSheetAt(0);

                                    fis.close();

                        } catch (Exception e) {

                                    e.printStackTrace();

                        }

            }

// returns the row count in a sheet

            public int getRowCount(String sheetName){

                        int index = workbook.getSheetIndex(sheetName);

                        if(index==-1)

                                    return 0;

                        else{

                        sheet = workbook.getSheetAt(index);

                        int number=sheet.getLastRowNum()+1;

                        return number;

                        }

            }

2. Log4J API: Working with Selenium or Appium you will find 2 kinds of logs. One is application log, which are user-defined logs and other one is selenium log,which are related to server log or selenium response log. The selenium log you can create when you have the version called X and 3.x, If you are using the latest API version, you would not able to generate the selenium logs, only you can generate application logs.Log4J configuration is very simple and you can configure it very easily. It has two APIs: Log4J 1 and Log4J 2.Compare to Log4J 2, Log4J1 has very good features and you will find it very comfortable and flexible. The first prerequisite is to add the dependency to your POM.xml file or add the jar file to your project. Once the dependency is added to your project, the log file will be auto generated.Then you need to call the class called logger.

Steps to configure Log4J:

Step 01: Go to maven repository -https://mvnrepository.com/.

Step 02: Download the Log4J jar file or copy the dependency from the repository.

Step 03: You can configure it through XML or properties file, here I am using the properties file for configuring Log4j.

Step 04: Go to your eclipse project, click on the src/main/resource and create a new folder called properties and create a new file with extension.properties(Log4J.properties).

Search the web

Step 05: Below is the Log4J properties file.

Properties file

You can find a different log level for example Debug, info, error, etc.Here I have chosen the highest level as INFO. Fileappender used to append logs in a file and also you can use the console appender, which will add the logs in a console.

Below is the properties file of Log4J and details explanation of it:

log4j.rootLogger=INFO, Appender

log4j.appender.Appender=org.apache.log4j.FileAppender

//below log is used to generate the log file at exact location where you want place your log file.

log4j.appender.Appender.File=src/test/resources/logs/app_${current.date}_log.txt

//Pattern layout is used to add the current timestamp

log4j.appender.Appender.layout=org.apache.log4j.PatternLayout

log4j.appender.Appender.layout.ConversionPattern=%-7p %d [%t] %c %x – %m%n

//When you write append = false means it will generate the fresh log everytime,the file will be overriden .When you make it true the log file will generate in same file.

log4j.appender.Appender.Append=false

//5000KB is the maximum size limit if it is exceed that,there will be BackupIndexupto 3 backupindex logs files will be generating.

log4j.appender.file.maxFileSize=5000KB

log4j.appender.file.maxBackupIndex=3

How to initiate/create Logs:

Step 01: Go to your utility folder, right-click on the folder and create a new class.

Step 02: Below is the log class:

public class TestLogs {

            public static Logger log = Logger.getLogger(TestLogs.class.getName());

            public static void main(String[] args) {

                        Date d = new Date();

                        System.out.println(d.toString().replace(“:”, “_”).replace(” “, “_”));

                        System.setProperty(“current.date”, d.toString().replace(“:”, “_”).replace(” “, “_”));

//give the log properties file path                  PropertyConfigurator.configure(“./src/test/resources/properties/log4j.properties”);

                        log.info(“This is the information log”);

                        log.error(“Here the error logs will be printed”);

            }

}

Step 03:Once you refresh the project, your log file will generate.

3. JavaMail API: JavaMail API is a third-party API. This is used to send an automated email.

Below are the detailed steps to use JavaMail API in selenium WebDriver .

Step 01: First prerequisite to use JavaMail API is to add the jar files to your project or to add the dependency to your pom.xml.

Step 02: Create a class called MonitoringMail for send a mail.

Below is the function for send an email:You have to provide mail server, from details,username,password,port name,subject of your email,message body of your email,attachment path and finally name of the attachment.

public class MonitoringMail

{

            //public static void sendMail(String mailServer, String from,String username, String password,String port, String[] to, String subject, String messageBody, String attachmentPath, String attachmentName) throws MessagingException, AddressException

            public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException

            {

                        boolean debug = false;

                        Properties props = new Properties();

                        props.put(“mail.smtp.starttls.enable”, “true”);

                        props.put(“mail.smtp.EnableSSL.enable”,”true”);

                        props.put(“mail.smtp.auth”, “true”);

                        props.put(“mail.smtp.host”, mailServer);

                        props.put(“mail.debug”, “true”);

            props.setProperty(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);  

            props.setProperty(“mail.smtp.socketFactory.fallback”, “false”);  

            props.setProperty(“mail.smtp.port”, “465”);  

            props.setProperty(“mail.smtp.socketFactory.port”, “465”);

                          Authenticator auth = new SMTPAuthenticator();

                            Session session = Session.getDefaultInstance(props, auth);

                        session.setDebug(debug);

}

4. JDBC Connection: This API helps to connect the database and writing queries and validating the results. You will find a different vendor to perform a JDBC connection for example MYSQL,SQL,MongoDB, etc.

Below are the steps to use JDBC Connection API:

Step 01: Go to Maven repository and search the required database to your project.

Step 02: Download the jar files or copy the dependency and paste it in your POM.XML.

Step 03:In order to make a JDBC connection,you should have the url,username and password to connect with a database.

Url- Database server url(e.g.ip:port/dbname, 172.68.1.1:3306/dbname).

Step 04: Click on this link https://mysql-com.en.softonic.com/download and download the mysql server. You will get setup file. Install it and it will ask you to provide the password. Provide the new password. Default user name is root.If you want to change, you can change it and continue the installation process.

Step 05: Open command prompt,enter the passwordwhich you had created earlier during installation. You will connect to database.

Step 06: Create a database and table.

Step 07: For database connection you will get one class called Driver Connection and you have to provide database name before which we used as a url, user name and password.Before the driver connection class you need to register the JDBC driver.

Below is the code for connecting JDBC:

Class.forName(TestConfig.driver);

                        con =DriverManager.getConnection(TestConfig.dbConnectionUrl, TestConfig.dbUserName, TestConfig.dbPassword);

Step 08:Go to your project utility and create a java class called DbManager. Below is the functionality for Db manager utility.

//Initializing the driver manager to get database connection.

                        try{

                        Class.forName(TestConfig.driver);

                        con =   DriverManager.getConnection(TestConfig.dbConnectionUrl, TestConfig.dbUserName, TestConfig.dbPassword);

}                      

}

//Get your query based on your requirement.

            public static ListgetQuery(String query) throws SQLException{

                        //String Query=”select top 10* from ev_call”;

                        Statement St = con.createStatement();

                        ResultSetrs = St.executeQuery(query);

                        List values = new ArrayList();

                        while(rs.next()){

                                    values.add(rs.getString(1));

                        }

Step 09: If you want to setup a database connection,create new class(TestDBConn) and you have to call DbManager.setMysqlDbConnection method in TestDBConn class. Once the database connection is established, write the query to fetch the results from database. Use getMySqlquery for mysql database and finally execute the TestDBConn.

Below is the code for TestDBConn class:

package testcases;

import java.sql.SQLException;

public class TestDBConn {

            public static void main(String[] args) throws ClassNotFoundException, SQLException {

                        DbManager.setMysqlDbConnection();

                        System.out.println(DbManager.getMysqlQuery(“select tutorial_author from selenium where tutorial_id = 2”));

            }

}

Leave a Reply

Your email address will not be published. Required fields are marked *