i

Selenium Step By Step Guide

Capturing screenshot, Handling tabs and pop-ups – Code

  1. Capturing screenshot and Send Email Results- Code:

We have a scenario where we have two test cases, and one Test case is passed while another gets failed. We need to capture the screenshot of the failed test case’s web page and send the test report over the mail.

Test class:

 

package SeleniumTest.SeleniumTest;

 

 

import java.io.File;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.ITestResult;

import org.testng.annotations.AfterClass;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.AfterSuite;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;

 

import com.relevantcodes.extentreports.DisplayOrder;

import com.relevantcodes.extentreports.ExtentReports;

import com.relevantcodes.extentreports.ExtentTest;

import com.relevantcodes.extentreports.LogStatus;

 

public class TestNGTest {

    ExtentReports extent;

                ExtentTest logger;

                WebDriver driver ;

               

                @BeforeClass

                public void startReport()

                {

                                extent=new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html",null, DisplayOrder.NEWEST_FIRST);

                                extent.addSystemInfo("Host Name","Software Testing blog")

                                      .addSystemInfo("Environment","Test Envt")

                                      .addSystemInfo("User Name","Kamal Gairola");

                                extent.loadConfig(new File(System.getProperty("user.dir")+"/extent-config.xml"));

                               

                }

               

                @BeforeMethod

                public void startDriver()

                {

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

        driver=new ChromeDriver();

        this.driver.get("https://selflearning.io/");

                               

                }

  @Test

  public void passTest() {

                 

                  logger=extent.startTest("passTest");

                  Assert.assertTrue(true);

                  logger.log(LogStatus.PASS, "passTest is passed");

                 

  }

 

  @Test

  public void failTest()

  {

                  logger=extent.startTest("failTest");

                  Assert.assertTrue(false);

                  logger.log(LogStatus.PASS, "failTest is passed");

  }

 

  @AfterMethod

  public void TestResult(ITestResult result) throws IOException

  {

                  if(result.getStatus()==ITestResult.FAILURE)

                  {

                                  logger.log(LogStatus.FAIL, "Test case"+result.getName());

                                  logger.log(LogStatus.FAIL, "Test case failed is "+result.getThrowable());

//getScreenshot() method is called from CaptureScreenshot class created in the same package

                                  String scrPath=CaptureScreenshot.getScreenshot(driver,result.getName());

                                  logger.log(LogStatus.FAIL,logger.addScreenCapture(scrPath));

                                  extent.endTest(logger);

                  }

  }

 

  @AfterClass

  public void completeTest()

  {

                 

                  extent.flush();

// SendMail method is called from the SendingMail class created in the same package

                  SendingMail.sendMail(System.getProperty("user.dir")+"/test-output/ExtentReport.html");

                 

 }

}

 

CaptureScreenshot Class:

package SeleniumTest.SeleniumTest;

 

import java.io.File;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.apache.commons.io.FileUtils;

 

 

public class CaptureScreenshot

{

    public static String getScreenshot(WebDriver driver, String testName) throws IOException

    {

       

        String timeFormat=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());

        TakesScreenshot scr=(TakesScreenshot)driver;

        File screenshotFile=scr.getScreenshotAs(OutputType.FILE);

        String destinationPath=System.getProperty("user.dir")+"/screenshot/"+testName+timeFormat+".png";

        File outputFile= new File(destinationPath);

        FileUtils.copyFile(screenshotFile, outputFile);

        return destinationPath;

    }

}

SendingMail class:

We use JavaMAil API for sending the email once the test gets completed and results are saved in project directory. We have created a separate class for the sending email and we have named it SendingMail class.

package SeleniumTest.SeleniumTest;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

                public class SendingMail {

                 public static void sendMail(String fileName) {

 

                  //object of Property file

                  Properties props = new Properties();

                  props.put("mail.smtp.host", "smtp.gmail.com");

                  props.put("mail.smtp.socketFactory.port", "465");

                  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");

                  props.put("mail.smtp.auth", "true");

                  props.put("mail.smtp.port", "465");

 

                  //Authentication handling

                  Session session = Session.getDefaultInstance(props,

                    new javax.mail.Authenticator() {

                     protected PasswordAuthentication getPasswordAuthentication() {

 

                     return new PasswordAuthentication(yourMailID, yourPassword);

 

                     }

 

                    });

 

                  try {

 

                   // Creating object of MimeMessage class

                   Message message = new MimeMessage(session);

                   message.setFrom(new InternetAddress("xyz@gmail.com"));

                   message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("abc@abc.com"));

                   message.setSubject("Testing Subject");

 

                   // Creating object to add multimedia type content

                   BodyPart messageBodyPart1 = new MimeBodyPart();

                   messageBodyPart1.setText("This is message body");

 

                   // Creating another object to add another content

                   MimeBodyPart messageBodyPart2 = new MimeBodyPart();

                   // Creating data source and pass the filename

                   DataSource source = new FileDataSource(fileName);

                   // setting the handler

                   messageBodyPart2.setDataHandler(new DataHandler(source));

 

                   // setting the file

                   messageBodyPart2.setFileName(fileName);

                   // Creating object of MimeMultipart class

                   Multipart multipart = new MimeMultipart();

 

                   // adding body part 1

                   multipart.addBodyPart(messageBodyPart2);

 

                   // adding body part 2

                   multipart.addBodyPart(messageBodyPart1);

 

                   // setting the content

                   message.setContent(multipart);

                   //Sending the email

                   Transport.send(message);

                   System.out.println("Email has been sent");

 

                  } catch (MessagingException e) {

 

                   throw new RuntimeException(e);

                  }

}

}