Automation Exceptions and Solutions

     We know that an exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. This block of code is called an exception handler.

     In real world scenario, while working with automation using Selenium WebDriver, automation engineer would definitely come across various exceptions which disrupts the test case execution. The automation script that you work with, sometimes work properly and sometimes it simply doesn’t work. For any script that you develop, make sure that you deliver the best quality code with proper exceptions handling techniques implemented.

     In this article, I would like to share the common exceptions while selenium automation execution and also the solutions to handle those exceptions. Following are the different types of exceptions in selenium,

WebDriverException

     WebDriverException arises when the your code tries to perform any action on the non-existing browser. For example, trying to use driver after closing the driver session.

WebDriver driver = new ChromeDriver();
driver.get(“https://journeyofquality.com/ “);
driver.close();
driver.findElement(By.id(“bu345”)).click();

Solution: You can handle this WebDriverException by using driver.close() after the completion of all tests at @AfterSuite annotation if you are using TestNG instead of using them after each test case that is after all the test execution has completed.

SessionNotFoundException

     SessionNotFoundException will occur when driver is trying to perform operations on the web application after the browser is quitted by driver.quit().

@Test
public void openJourneyOfQuality() {
driver.get(“https://journeyofquality.com/ “);
Assert.assertEquals(“Journey”, driver.getTitle());
driver.quit();
Assert.assertEquals(“https://journeyofquality.com/ “, driver.getCurrentUrl());
}

Solution: This exception can be handled by using driver.quit() after the completion of all tests instead of using them after each test case. This can lead to issues when driver instance becoming null and following test cases try to use it without initializing. We can kill the driver instance after all the test execution has completed and hence we can add them up at @AfterSuite of TestNG annotation.

StaleElementReferenceException

     User would come across StaleElemenReferenceException mainly when Selenium navigates to a different page, come backs to the same old page and performs operations on the old page which is no longer available. Technically, it occurs when the element defined in the script is not found in the cache memory and script is trying to locate it that particular element. When we inspect and locate an element on a page using Selenium, it is stored in a cache memory which gets deleted when the driver navigates to another page during execution. When user navigates back to old page and then while trying to access the cache removed element on the old page, we will get StaleElementReferenceException during the automation script execution.

Solutions:

  • Refresh the webpage and perform action on that web element.
  • Include the web element on try-catch block within for loop to get the element and perform the action. Once it perform the action, it will break from the loop.

for (int value = 0; value <= 2; value++) {
try {
driver.findElement(By.xpath(“webElement”)).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

  • Wait for the element till available by using ExpectedConditions,

wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“webElement”)));

NoSuchElementException

     NoSuchElementException occurs, when the element locators we provided in the Selenium script is unable to find that web element on the web page. Probably this will happen in two ways,

  • When we have provided an incorrect locator and trying to find the web element.
  • We have provided correct locator, but the web element related to the locator is not available on the web page. That means the action performed before loading that element on the web page.

@Test
public void testJourney() {
driver.get(“https://journeyofquality.com/ “);
try {
driver.findElement(By.id(“invalidelement”)).click();
} catch (NoSuchElementException e) {
System.out.println(“No Such Element exceptional case”);
}
}

     In the above code, trying to locate an element with id invalidelement on website page. When the element is not found, the application throws NoSuchElementException.

Solution: Make sure that the locator (XPath/Id) provided is correct or try to use the explicit wait methods for the presence of element and then perform the action on it. For example,

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“invalidelement”)));

ElementNotVisibleException

     ElementNotVisibleException is thrown when WebDriver tries to perform an action on an invisible web element, which cannot be interacted with since element is in a hidden state. For example, there is no button displayed on the web page and if there is HTML code related to the button, then on trying to click on that particular button using locators in the automation script and we will get ElementNotVisibleException. These exception can happen even if the page has not loaded completely and when user tries to interact with an element.

Solution: We have to wait until that particular element becomes visible on web page. To tackle this you can use the explicit wait methods in Selenium. For example,

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“invisibleElement”));

NoSuchFrameException

     On the webpage, user may have to deal with HTML documents that are embedded inside another HTML document which are called as iframe. In order to work with the web elements on any iframe, we have to first switch to that particular iframe in Selenium by using frame-name or frame-ID and then inspect and locate the respective web elements inside the iframe. NoSuchFrameException occurs, when the driver in the Selenium script is unable to find the frame on the web page to switch which happens when the driver is switching to an invalid or non-existing iframe.

Solution: We have to wait until that particular frame to be available on web page. To tackle this, you can use the explicit wait methods in Selenium. For example,

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.frameToBeAvaliableAndSwitchToIt(frame_id));

NoAlertPresentException

     Alert is a pop-up which provide important information to users or asking for perform certain operation like reading the messages on the alerts or accepting the alert by pressing OK button on the alert or dismissing the alert by pressing CANCEL button etc. In order to work with Alert pop-ups, we have to first switch to Alert and then perform operations on Alert window. NoAlertPresentException occurs when the driver in the script is unable to find the Alert on the web page to switch when the driver is switching to an invalid or non-existing Alert pop-up. Sometime NoAlertPresentException exception is thrown even if the alert is not loaded completely.

Solution: To handle NoAlertPresentException include the script inside try-catch block and provide explicit wait for the alert to be available as shown below.

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());

NoSuchWindowException

     We know that Selenium automates Web applications only, and in real time we may have to deal with browser windows which will be opened when you click on buttons or links. In order to interact with the Web Elements on any browser pop-up window, we have to handle all the opened windows and then locate the respective web elements inside the pop-up window. NoSuchWindowException occurs when the driver in the script is unable to find the pop-up window on the web page to switch. NoSuchWindowException is thrown if the window handle doesn’t exist or is not available to switch.

Solution: We would iterate through all the active windows handles and perform the desired actions. For example,

for(String handle: driver.getWindowHandles()) {
try {
driver.switchTo().window(handle);
} catch (NoSuchWindowException e) {
System.out.println(“No such window exceptional case”);
}
}

TimeoutException

     Waits are mainly used in WebDriver to avoid the exception like ElementNotVisibleException which occurs while trying to click on a button before the page is completely loaded. This exception occurs when a command takes more than the wait time completion. However, if the components doesn’t load even after the wait time mentioned, the exception org.openqa.selenium.Timeoutexception will be thrown.

Solution: To avoid this exception, waits commands are added either implicit, explicit or fluent wait.

Implicit Wait:

     The Implicit Wait in Selenium is used to tell the web driver to wait for a certain amount of time before it throws a NoSuchElementException. The default setting is 0. Once we set the time, the web driver will wait for the element for that time before throwing an exception. For example,

driver.manage().timeouts().implicitlyWait(15,TimeUnit.SECONDS) ;
driver.get(“https://journeyofquality.com/ “);

     In the above code, an implicit wait of 15 seconds is added. If the page https://journeyofquality.com/ doesn’t load in 15 seconds, then TimeoutException will be thrown.

Explicit Wait:

     The Explicit Wait in Selenium is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or maximum time exceeded before throwing ElementNotVisibleException exception. It is an intelligent kind of wait, but it can be applied only for specified elements. We already discussed few examples above related to explicit wait like,

wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“webElement”)));
wait.until(ExpectedConditions.frameToBeAvaliableAndSwitchToIt(frame_id));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“invisibleElement”))
;

Fluent Wait:

     The Fluent Wait in Selenium is used to define maximum time for the web driver to wait for a condition, as well as the frequency with which we want to check the condition before throwing an ElementNotVisibleException exception. It checks for the web element at regular intervals until the object is found or timeout happens. Frequency is setting up a repeat cycle with the time frame to verify or check the condition at the regular interval of time. Below is the sample implmentaion for fluent wait,

Wait wait = new FluentWait(WebDriver driver)
.withTimeout(Duration.ofSeconds(SECONDS))
.pollingEvery(Duration.ofSeconds(SECONDS))
.ignoring(Exception.class);

Overall Exception Handling Solutions

     In order to handle these above types of Selenium exceptions, we will use following exception handling mechanism,

Throw: Throw keyword is used to throw exception to the runtime to handle it.

public static void anyMethod() throws Exception{
try{
// write your code here
}catch (Exception e){
// Do whatever you wish to do here
// Now throw the exception back to the system
throw(e);
}
}

Multiple Catch Blocks: You can use multiple catch() blocks to catch different types of exception. The syntax for multiple catch blocks looks like the following:

public static void anyMethod() throws Exception{
try{
// write your code here
}catch(ExceptionType1 e1){
//Code for Handling the Exception 1
}catch(ExceptionType2 e2){
//Code for Handling the Exception 2
}

Try/Catch: A try block encloses code that can potentially throw an exception. A catch() block contains exception-handling logic for exceptions thrown in a try block. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

public static void anyMethod() throws Exception{
try{
// write your code here
}catch(Exception e){
//Code for Handling the Exception
}
}

Finally: A finally block contains code that must be executed whether an exception is thrown or not:

public static void anyMethod() throws Exception{
try{
// write your code here
}catch(ExceptionType1 e1){
//Code for Handling the Exception 1
}catch(ExceptionType2 e2){
//Code for Handling the Exception 2
}
finally{
//The finally block always executes.
}
}

     I hope you got an idea on various common selenium exceptions, the solutions and the general way to handle those exceptions. Try to implement these exception handling mechanism in your automation script and handle these runtime anomalies.

make it perfect!

Send Automation Reports as Mail Report

screen-shot-2012-11-13-at-11-25-44-pm

    Automation test reports are one of the important deliverable of Automation executions. Getting those automation reports in the mail automatically is the another important concept. Here, I would like to share the information about how to send your automation reports as mail report with attachment while automation of your application with Java or C# languages.

Send automation test reports with Java language:

Prerequisites:

        Need to add javax.mail dependency in pom.xml of your automation project (if it is a Maven project. Otherwise need to add javax.mail jar in your Java Build Path of your Java project). Following is the javax.mail dependency,

<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>

Following sendMailReport() method helps to send test automation reports with attachment,

public static void sendMailReport() throws AddressException, MessagingException {
String subject = “”, message = “”, maillist = “”, EMAIL_REPORT_FOLDER = “”;
subject = “Automation Test Report_”;
message = “Please find the attached report to get details.”;
maillist = “mail_lists_of_recipients”;
EMAIL_REPORT_FOLDER = “path_to_automation_report_folder”;
Properties properties = new Properties();
properties.put(“mail.smtp.host”, “smtp.gmail.com”);
properties.put(“mail.smtp.port”, “587”);
properties.put(“mail.smtp.auth”, “true”);
properties.put(“mail.smtp.starttls.enable”, “true”);
final String userName;
final String password;
userName = “sender_mail_address”;
password = “sender_mail_account_password”;
properties.put(“mail.user”, userName);
properties.put(“mail.password”, password);

Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
DateFormat dff = new SimpleDateFormat(“EEE MMM dd, yyyy HH:mm:ss z”);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(maillist));
msg.setSubject(subject + ” – ” + dff.format(new Date()).toString());
msg.setSentDate(new Date());

// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, “text/html”);

// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

// adds attachments
List<String> filesList = new ArrayList<String>();
File[] files = new File(System.getProperty(“user.dir”) + EMAIL_REPORT_FOLDER).listFiles();
for (File file : files) {
if (file.isFile()) {
filesList.add(System.getProperty(“user.dir”) + EMAIL_REPORT_FOLDER + “/” + file.getName());
}
}
if (filesList != null && filesList.size() > 0) {
for (String filePath : filesList) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail’s content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}

Send automation test reports with C# language:

       The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. Following Send_Report_In_Mail() method helps to send test automation reports with attachment,

public void Send_Report_In_Mail()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(“smtp.gmail.com”);
mail.From = new MailAddress(“sender_mail_address”);
mail.To.Add(“mail_lists_of_recipients”);

StringBuilder TimeAndDate = new StringBuilder(DateTime.Now.ToString());
TimeAndDate.Replace(“/”, “_”);
TimeAndDate.Replace(“:”, “_”);

mail.Subject = “Automation Test Report_”+ TimeAndDate;

mail.Body = “Please find the attached report to get details.”;

string actualPath = AppDomain.CurrentDomain.BaseDirectory.Replace(“\\bin\\Debug”, “\\Test_Execution_Reports”); //Reports should stored in Test_Execution_Reports folder

var mostRecentlyModified = Directory.GetFiles(actualPath, “*.html”)
.Select(f => new FileInfo(f))
.OrderByDescending(fi => fi.LastWriteTime)
.First()
.FullName;

Attachment attachment;
attachment = new Attachment(mostRecentlyModified);
mail.Attachments.Add(attachment);

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(“sender_mail_address”, “sender_mail_account_password”);
SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);

}

     You can use those method in @AfterSuite if you are using TestNG. In case of NUnit(C#), you can use those method in [OneTimeTearDown]. Try to use above code snippet in your automation scripts to send your automation test report as mail report automatically.

make it perfect !

Parallel Test Executions in Automation – TestNG and NUnit

cross_platform

      One day I got an opportunity to automate an application using both Selenium Java and Selenium C#, that was the specific requirement of the customer to do it on both Java and C#. Later customer said to execute different test cases from different class in different browsers in parallel mode. Their aim was to complete the execution of all test cases in a minimum amount of time. Here, I would like to share how I achieved the parallel execution in both Selenium Java and Selenium C#.

Parallel Execution in Selenium Java Automation:

       In case of Selenium Java, I used TestNG’s parallel execution capability with support of attribute parallel=”tests” along with the tag in TestNG XML. I have created two tags to launch two different driver instances. Following is the sample testng.xml which I used for parallel execution:

<suite name=”TestSuite” parallel=”tests” preserve-order=”true”>
<test name=”Test In Google Chrome”>
<parameter name=”browserName” value=”Chrome”/>
<classes>
<class name=”com.test.TestSuiteClassSmoke”/>
</classes>
</test>
<test name=”Test In Firefox”>
<parameter name=”browserName” value=”Firefox”/>
<classes>
<class name=”com.test.TestSuiteClassSanity”/>
</classes>
</test>
</suite>

      In the above testng.xml file, contains one test to run all the test cases of the Smoke Suite in Google Chrome browser and the second test to run all the test cases of the Sanity Suite in Firefox. Both browser instances are start same time and execute in parallel. TestSuiteClassSanity and TestSuiteClassSmoke classes extends AutomationBase class to get the driver instances for execution. Following is the actual implementation of AutomationBase class:

@BeforeClass()
@Parameters({“browserName”})
public void SetUp(String browserName) throws IOException, InterruptedException
{
try {
if(browserName.equalsIgnoreCase(“chrome”)){
// implement code to start chrome driver session
}
else if(browserName.equalsIgnoreCase(“firefox”)){
// implement code to start firefox driver session
}
}catch (Exception e) {
e.printStackTrace();
}
}

Parallel Execution in Selenium C# Automation:

      In case of Selenium C#, there is no direct capability like TestNG to achieve the parallel execution of test cases in different instances of browsers. I used NUnit attributes just above in all test classes and that test class extends AutomationBase class. Used following NUnit attributes:

  • [TestFixture(“chrome”)]
  • [TestFixture(“firefox”)]
  • [Parallelizable]

        Added a parameterized constructor (the parameter should be browserName) and call StartBrowser(browserName) method inside the constructor. StartBrowser (browserName) method is implemented in AutomationBase class. Following is the sample implementation that I have done in the test class:

using NUnit.Framework;
namespace com.test.testcases
{
[TestFixture(“chrome”)]
[TestFixture(“firefox”)]
[Parallelizable]
public class TestModuleClass: AutomationBase
{
public TestModuleClass(string browserName)
{
StartBrowser(browserName);
}

[Test, Order(1)]
public void TC_001_SampleTest()
{
//Your test steps
}
}
}

    In AutomationBase class, I have added new method StartBrowser(String browserName) to identify the requested browser for execution and implemented the logic to drive chrome and firefox drivers. Following is the implementation of StartBrowser,

public IWebDriver StartBrowser(String browserName)
{
try
{
if (browserName.ToLower().Equals(“”))
{
throw (new Exception(“BROWSER_NAME is not specified”));
}
if (browserName.ToLower().Equals(“chrome”))
{
// implement code to start chrome driver session
}
if (browserName.ToLower().Equals(“firefox”))
{
// implement code to start firefox driver session
}
}
catch (Exception e)
{
throw (e);
}
return driver;
}

     You can try above mechanisms of parallel executions in automation for both Selenium Java and Selenium C#.

make it perfect !

Extent Reports in Automation – TestNG

maxresdefault

     TestNG itself, providing an HTML report in test-output folder. I had a thought of building custom report for automation, after that I built one PDF customized report using iText PDF Java library and took more effort to build it. Later I thought to build a custom beautiful high rich HTML reports with minimum effort; that time Extent Report comes into my mind. Here, I would like to share the details on the integration and implementation of Extent Report utility in Automation test classes that built with TestNG.

Prerequisites to Generate Extent Reports:

  1. Java should be installed and setup Java
  2. TestNG maven dependency should be available
  3. Selenium maven dependency should be available
  4. Extent Report Maven dependency should be available
  5. extent-config.xml – It allows to configure HTML Report

Steps To Generate Extent Reports:

  1. Firstly, create a maven project.
  2. Add TestNG dependency to pom.xml of project in eclipse.
  3. Add selenium-java and selenium-server dependencies to pom.xml of  project in eclipse
  4. Extent Report Maven dependency (version: 2.41.2) should available and added in pom.xml project in eclipse.
  5. Create a java class say ‘SeleniumExtentReport’ and add following code to it,

package com.journeyofquality.test;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
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.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class SeleniumExtentReport {
ExtentReports extentReport;
ExtentTest extentTest;
WebDriver driver;

@BeforeSuite
public void beforeSuite() {
//In before suite we are creating HTML report template, adding basic information to it and load the extent-config.xml file

extentReport = new ExtentReports(System.getProperty(“user.dir”) + “/test-output/SeleniumExtentReport.html”,
true);
extentReport.addSystemInfo(“Host Name”, “JourneyofQuality”).addSystemInfo(“Environment”, “Automation Testing”)
.addSystemInfo(“User Name”, “Sanoj”);
extentReport.loadConfig(new File(System.getProperty(“user.dir”) + “\\extent-config.xml”));
}

@BeforeClass
public void beforeClass() {
System.setProperty(“webdriver.chrome.driver”, );
driver = new ChromeDriver();
}

@BeforeMethod
public void beforeMethod(Method method) {
//In before method we are collecting the current running test case name
String className = this.getClass().getSimpleName();
extentTest = extentReport.startTest(className + “-” + method.getName());
}

@Test
public void passTest() {
Assert.assertTrue(true);
}

@Test
public void failTest() {
driver.get(“http://google.com&#8221;);
Assert.assertEquals(driver.getTitle().toString(), “Journey”);
}

@Test
public void skipTest() {
throw new SkipException(“Skipping – This is not ready for testing “);
}

@AfterMethod
public void getResult(ITestResult result, Method method) throws Exception {
//In after method we are collecting the test execution status and based on that the information writing to HTML report
if (result.getStatus() == ITestResult.FAILURE) {
extentTest.log(LogStatus.FAIL, “Test Case Failed is ” + result.getName());
String screenshotPath = SeleniumExtentReport.capture(driver, result.getName());
extentTest.log(LogStatus.FAIL, “Error Details :- \n” + result.getThrowable().getMessage()
+ extentTest.addScreenCapture(screenshotPath));
}
if (result.getStatus() == ITestResult.SKIP) {
extentTest.log(LogStatus.SKIP, “Test Case Skipped is ” + result.getName());
}
if (result.getStatus() == ITestResult.SUCCESS) {
extentTest.log(LogStatus.PASS, “Test Case Passed is ” + result.getName());
}
}

@AfterSuite
public void endReport() {
//In after suite stopping the object of ExtentReports and ExtentTest
extentReport.endTest(extentTest);
extentReport.flush();
driver.quit();
}

/**

* To Capture the Screenshot and return the file path to extent report fail
* cases
*
* @param driver
* @param screenShotName
* @return
* @throws IOException
*/
private static String capture(WebDriver driver, String screenShotName) throws IOException {
String dest = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(“dd-mm-yyyy h-m-s”);
Date date = new Date();
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
dest = System.getProperty(“user.dir”) + “\\ErrorScreenshots\\” + screenShotName + dateFormat.format(date)
+ “.png”;
File destination = new File(dest);
FileUtils.copyFile(source, destination);
} catch (Exception e) {
e.getMessage();
System.out.println(e.getMessage());
}
return dest;
}
}

Code Explanation:

  • Imported two classes ExtentReports and ExtentTest.
    • ExtentReportsBy using this class we set the path where our reports need to generate.
    • ExtentTestBy using this class we could generate the logs in the report.
  • Took three methods with @Test annotation such as passTest, failTest and skipTest and a method beforeSuite with @BeforeSuite annotation, beforeMethod with @BeforeMetod annotation, another method getResult with @AfterMethod annotation and finally, endReport with @AfterSuite annotation.
  • Here my intention is to generate a report with all the three types of results such as Pass, Fail and Skip.
  • Used object of ExtentReports class (i.e., extentReport) in the beforeSuite method which was assigned to @BeforeSuite annotation to generate the HTML report in the required path.
  • Used object of ExtentTest class (i.e., extentTest) in beforeMethod to get the name of currently executing test case. Also, extentTest object used in getResult method which was assigned to @AfterMethod annotation to write logs in the report.
  • Used ITestResult class in the @AfterMethod to describe the result of a test.

extent-config.xml: 

     By using this external XML file (extent-config.xml), we could change the details such as Report Theme (either standard or dark), Report Title, Document Title etc., We use extent object and use loadConfig() method to load this XML file.

<?xml version=”1.0″ encoding=”UTF-8″?>
<extentreports>
<configuration>
<!– report theme –>
<!– standard, dark –>
<theme>standard</theme>
<!– document encoding –>
<!– defaults to UTF-8 –>
<encoding>UTF-8</encoding>
<!– protocol for script and stylesheets –>
<!– defaults to https –>
<protocol>https</protocol>
<!– title of the document –>
<documentTitle>JourneyOfQuality</documentTitle>
<!– report name – displayed at top-nav –>
<reportName>JourneyOfQuality</reportName>
<!– report headline – displayed at top-nav, after reportHeadline –>
<reportHeadline>Automation Report</reportHeadline>
<!– global date format override –>
<!– defaults to yyyy-MM-dd –>
<dateFormat>yyyy-MM-dd</dateFormat>
<!– global time format override –>
<!– defaults to HH:mm:ss –>
<timeFormat>HH:mm:ss</timeFormat>
<!– default style override –>
<theme></theme>
<!– custom javascript –>
<scripts>
<![CDATA[
$(document).ready(function() {
$(“.logo-content”).hide();
$(“.logo-container”).html(“JourneyOfQuality”);
$(‘#parentNodes’).prop(“checked”, true).click();
$(‘#test-count-setting > div.modal-footer > a’)[0].click();
});
]]>
</scripts>
<!– custom styles –>
<styles>
<![CDATA[
]]>
</styles>
</configuration>
</extentreports>

     Refresh the project after execution of above SeleniumExtentReport.java file. You could find an HTML file named “SeleniumExtentReport.html” in your test-output folder. Copy the location of the “SeleniumExtentReport.html” file and open it by using any browser. You could see beautiful high rich HTML reports as shown below.

Capture

Capture1

Try to implement the above mentioned custom report mechanism in your Selenium – Java -TestNG and enjoy automation.

make it perfect !

Selenium Automation using C# (NUnit)

DYLSVhtWAAA5qn9seleniumwithC

     In the previous post, we discussed about Selenium C# and MSTest framework. Another day, I got an opportunity to write selenium automation using C# language and NUnit framework. Prior to scripting, I started the configuration from the scratch to achieve my selenium scripting using C# and NUnit. Here I would like to share my experience with configuration and scripting part,

Steps for install and configure Visual Studio:

Step 1: Navigate to the URL https://www.visualstudio.com/downloads/ and Click on the ‘Free download’ button displayed on Visual Studio Community 2017 tab.
Step 2: Open the exe downloaded. Click on ‘Yes’ if asked for Admin Rights.
Step 3: A popup will appear. Click on ‘Continue’ button.
Step 4: In the next screen, select the check-boxes for

  • Universal Windows Platform development
  • .Net desktop development

Click on ‘Install.’ Wait for installation of each component to complete. Files are 16GB in size and will take time.
Step 5: A pop up will be displayed. Click on ‘Restart’ button (if required).
Step 6: Once the machine is restarted, search for “Visual Studio 2017” on the start menu and click on the search result. In the next screen, Click on “Not now, maybe later” link if you do not have an existing account.
Step 7: In the next screen,

  • Select color theme of your liking
  • Click the button “Start Visual Studio'”

Step 8: Visual Studio ‘Get Started’ screen will appear.

Set up Visual Studio with Selenium WebDriver:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “Selenium”.
  2. Select the first search result “Selenium.WebDriver”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click on ‘Install’.
  6. Select second search result “Selenium.Support”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Set up Visual Studio with NUnit Framework:

Step 1: Navigate to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
Step 2: In the next window,

  1. Search for “NUnit”
  2. Select the search result “NUnit”
  3. Check the project checkbox
  4. Select the desired version.
  5. Click Install.
  6. In the same window, select search result “NUnit3TestAdapter”
  7. Check the project checkbox.
  8. Select the desired version.
  9. Click on ‘Install’.

Create a new project in Visual Studio:

Step 1: In the File Menu, Click New > Project
Step 2: In the next screen,

  1. Select the option ‘Visual C#’
  2. Click on Console App (.Net Framework)
  3. Enter project name.
  4. Click OK

Step 3: You will be able to see the created project.

     Now the configurations and project is ready, next you can add one C# class file to project and start writing your first script for automation as below. I used this class file to start my C# scripting for selenium automation,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using System.Threading;

namespace seleniumTestProject
{
[TestFixture]
public class SeleniumTest
{
public IWebDriver driver; //declare the driver object

[OneTimeSetUp]
public void BeforeClass()
{
driver = new ChromeDriver(“path_to_chromedriver.exe”); //initialize the ChromeDriver instance
driver.Url = “https://www.google.co.in/&#8221;; //load application URL
}

[SetUp]
public void BeforeTest()
{
//You can write any precondition to perform prior to each test cases
}

[Test]
public void GoogleSearchTest()
{
driver.FindElement(By.Id(“lst-ib”)).SendKeys(“Journey of Quality”);
}

[TearDown]
public void AfterTest()
{
driver.Close();
}

[OneTimeTearDown]
public void AfterClass()
{
driver.Quit();
}
}
}

     Try the above configuration and scripting using C# for Selenium Automation from your end. I recommend everyone to use NUnit framework than MSTest framework for Selenium C# scripting. NUnit provides straight-froward scripting when use their annotations. In case of MSTest, we must declare the method as static and should possess one parameter when use [AssemblyInitialize] or [ClassInitialize]. In case of NUnit, no need to declare the method as static when uses [OneTimeSetUp] or [SetUp].

make it perfect !