Monday, December 22, 2014

Selenium-WebDriver Automation Logger Class using Junit


Logger is a utility class in java.that allow us to log messages in code.

Use of Logger Class:

* Used to generate logs from Test
* Log error message in logs
* Format logs

Program Explanation:
  1. Opening browser
  2. Navigating to gmail
  3. Filling username and password 
  4. Giving wrong element to Siginbutton (i.e "Changing to signin ) to get error logs in log file
  5. Closing browser




Source code.

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.IOException;
import java.util.Formatter;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import  java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class testlog {
WebDriver driver;
//import log class
private static Logger logger=Logger.getLogger(testlog.class.getName());
//save log in somewhere
Handler filehandler=null;
//To change format of the log
SimpleFormatter formatter=null;

@Before
public void startup() throws SecurityException, IOException
{
//Save log file in root directory
filehandler =new FileHandler("./gmail.log");
formatter=new SimpleFormatter();
filehandler.setLevel(Level.ALL);
filehandler.setFormatter(formatter);
logger.addHandler(filehandler);
//Printout information using logger class
logger.info("Start the Test");
driver=new FirefoxDriver();
}
@After
public void end()
{
//Printout information using logger class
 logger.info("End the testcase");
 driver.quit();
}
@Test
public void login()
{
//Printout information using logger class
logger.info("Run Testcase");
driver.get("http://www.gmail.com");
driver.findElement(By.name("Email")).sendKeys("kk.prashanth65@gmail.com");
        driver.findElement(By.name("Passwd")).sendKeys("test123");
        
        //Make webelement wrong and get the error using Log "Change to signIn to signin put it in try/catch"
        try
        {
        //element not found
        driver.findElement(By.name("signin")).click();
        }
        catch(Exception e)
        {
        //Make Leve to severe using log and also printing stacktrace
        logger.log(Level.SEVERE,"Severe error occured"+e);
        }
        
}

}


Note :

After running the above code you get the log file in root directory

Hope you like this post.
Hit LIKE button on facebook.










3 comments: