Quantcast
Channel: Pochampalli IT Labs
Viewing all 261 articles
Browse latest View live

Tip : None of the features at [classpath:features] matched the filters: [@scenario_AddMarketingAccount, @scenario_AddMarketingUser] OR tags for command line execution of cucumber scenarios

$
0
0
Hi,

If we try to provide tags individually as below in main method for command line usage, we may end-up getting the error message saying .. None of the features at classpath matched the filters.

"-t","@scenario_AddMarketingAccount,
"-t","@scenario_AddMarketingUser",


None of the features at [classpath:features] matched the filters: [@scenario_AddMarketingAccount, @scenario_AddMarketingUser]

0 Scenarios

0 Steps
0m0.000s

Provide a single tag with comma separated literals/scenario tags. 
i.e., 
"-t","@scenario_AddMarketingAccount,@scenario_AddMarketingUser"

Below is how the tags should be written for CLI (command line interface)

package com.sadakar.selenium.common;
importorg.openqa.selenium.WebDriver;

publicclassBasePage{

publicstatic WebDriver driver;

publicstaticvoidmain(String args[])throws Throwable{
try{
cucumber
.api.cli.Main.main(
new String[]{
"classpath:features",
"-g","com.sadakar.cucumber.stepdefinitions/",
"-g","com.sadakar.cucumber.common",
"-t","@scenario_AddMarketingAccount,@scenario_AddMarketingUser",
"-p","pretty",
"-p","json:target/cucumber-reports/Cucumber.json",
"-p","html:target/cucumber-reports",
"-m"
}
);
}
catch(Throwable e){
e
.printStackTrace();
System
.out.println("Main method exception");
}
}
}


NOTE : 
When you run executable jar file, it executes ALL the scenarios given with "-t" tag.

1) Build the jar file 
clean compile assembly:single install

2) Run the jar file
java -DtestEnv=local -jar SADAKAR_POC-0.0.1-SNAPSHOT-jar-with-dependencies.jar

Core Java : Cannot make a static reference to the non-static field

$
0
0
If you try to  access an instance variable or say non-static variable in a static method, you would end up with static reference error message.

For instance, in the following example, variable "a" is class variable/non-static instance variable and if accessed directly in the static method, say in this case it is main method, it would throw the reference exception.

NonStaticDataMemberInStaticMethod.java
package static1.method;

publicclassNonStaticDataMemberInStaticMethod{

int a=10;// non static variable
publicstaticvoidmain(String args[]){
System
.out.println(a);
}

}


Error Message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static field a

at static1.method.NonStaticDataMemberInStaticMethod.main(NonStaticDataMemberInStaticMethod.java:7)

Solution:
1) Create an Object
2) Call/print the non static variable using object.

package static1.Variable;

publicclassNonStaticDataMemberInStaticMethod{

int a =10;//non static variable
publicstaticvoidmain(String args[]){

NonStaticDataMemberInStaticMethod myObj=new NonStaticDataMemberInStaticMethod();
System
.out.println(myObj.a);
}

}




- Sadakar Pochampalli 

C# : Error CS0120 An object reference is required for the non-static field, method, or property

$
0
0
In C#, if you try to print a non-static variable from static method, you will see the reference error message.


Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'Car.color' ConsoleApp3 C:\Users\sadakar\source\repos\ConsoleApp3\ConsoleApp3\Oops\ClassesAnbObjects\Car.cs 15 N/A


I wanted to check this example both in C# and Core Java and so if you are wondering how the similar behavior appears in core  java , take a look at this example@


usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceConsoleApp3.Oops.ClassesAnbObjects
{
classCar
{
string color = "red";
staticvoidMain(string[] args)
{
Car myObj =
new Car();
Console.WriteLine(
color);

Console.ReadLine();
}
}
}

Solution:
1) Create an Object
2) Call/print the non static variable using object.

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespaceConsoleApp3.Oops.ClassesAnbObjects
{
classCar
{
string color = "red";
staticvoidMain(string[] args)
{
Car myObj = new Car();
Console.WriteLine(
myObj.color);

Console.ReadLine();
}
}
}




References: 
https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop

Selenium installation in Eclipse and launch a website using navigate().to() method

$
0
0
Hi ,

This tutorial is intended to written for beginners and in this example, we would see how to set-up and launch a website in chrome browser (for example: https://jasper-bi-suite.blogspot.com/) using java selenium.

1. Download Eclipse zip from  https://www.eclipse.org/downloads/
2. Install java 1.8 or later and set path & class path in windows os.
3. Download suitable chromedriver.exe from https://chromedriver.chromium.org/downloads
      NOTE : This example is tested on : Version 81.0.4044.138 (Official Build) (64-bit)
4. Download selenium jar files and configure in Eclipse Build Path as (Referenced Libraries)
      https://www.selenium.dev/downloads/
5. Write FirstTestCase.java class with the code shown in below.
6. Run as "Java Applicaiton".

In the java class, ensure to have the following : 
1)  System set property  -  using this call the chromedriver.exe
2)  Declaring driver - driver declaration
3)  navigate().to - method to navigate to a given site.
4)     ChromeOptions options =new ChromeOptions();
         .......... Google Chrome Browser Options.............
        driver =new ChromeDriver(options);

Watch this ~15 sec video for execution of this case.



importjava.util.concurrent.TimeUnit;
/**
* @author Sadakar Pochampalli
*/
importorg.openqa.selenium.PageLoadStrategy;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.chrome.ChromeDriver;
importorg.openqa.selenium.chrome.ChromeOptions;

publicclassFirstTestCase{

publicstaticvoidmain(String[] args){

System.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver_win32\\chromedriver.exe");

WebDriver driver ;

ChromeOptions options =new ChromeOptions();

//options.addArguments("--headless");
options.addArguments("--disable-gpu");
options.addArguments("start-maximized");
options.setPageLoadStrategy(PageLoadStrategy.NONE);
options.addArguments("--allow-insecure-localhost");
options.addArguments("--allow-running-insecure-content");
options.addArguments("--ignore-certificate-errors");
options.addArguments("--no-sandbox");
options.addArguments("--window-size=1280,1000");
options.setCapability("acceptSslCerts",true);
options.setCapability("acceptInsecureCerts",true);
  driver =new ChromeDriver(options);

driver.navigate().to("https://jasper-bi-suite.blogspot.com/");
driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//driver.close();

}
}

Locators for selenium | linkText Example

$
0
0
Hi,

In this post, you will see the demonstration of "linkText" locator usage. For the purposes, I took my blog-site https://jasper-bi-suite.blogspot.com/.

linkText is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action.

For instance, navigate to "Services" page from the site.
Let's see how to perform/navigate to Services page using "Services" text from the following HTML script.
<ahref="https://jasper-bi-suite.blogspot.com/p/contact-information.html">Services </a>

The following statement identifies "Services" link on the page and does the click action.
 driver.findElement(By.linkText("Services")).click();

Take a look at the complete java code at the bottom or watch below 1 min video tutorial for end-to-end execution.

Screenshot: 

Watch this 1 min video tutorial ( change quality to 720p)
linkTextDemo.java
package selenium.locators.examples;
//linkText example
importjava.util.concurrent.TimeUnit;
importorg.openqa.selenium.By;
importorg.openqa.selenium.JavascriptExecutor;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.chrome.ChromeDriver;

publicclasslinkTextDemo{

publicstaticvoidmain(String[] args){

WebDriver driver
;

System
.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");
System
.setProperty("webdriver.chrome.silentOutput","true");

driver
=new ChromeDriver();

driver
.navigate().to("https://jasper-bi-suite.blogspot.com/");
driver
.manage().window().maximize();

driver
.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//linkText
driver.findElement(By.linkText("Services")).click();

JavascriptExecutor js
=(JavascriptExecutor) driver;
js
.executeScript("window.scrollBy(0,550)");

//driver.close();

}
}


- Sadakar Pochampalli 

Locators for selenium | id locator example | facebook login automation example in java-selenium

$
0
0
Hi,

In this post, you will see the demonstration of "id" locator usage. 

"id" is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action.

For instance, Login to facebook site @ http://www.facebook.com
Let's see how to identify the ids of login elements for facebook web application.

"Email or Phone" text input HTML
<inputtype="email"class="inputtext login_form_input_box"name="email"id="email"data-testid="royal_email">

"Password" text input HTML
<inputtype="password"class="inputtext login_form_input_box"name="pass"id="pass"data-testid="royal_pass">

"Log In" button HTML
<inputvalue="Log In"aria-label="Log In"data-testid="royal_login_button"type="submit"id="u_0_b">


The following statements identifies the above 3 elements using id attribute on the page.
 driver.findElement(By.id("email")).sendKeys("test123@gmail.com");
 driver.findElement(By.id("pass")).sendKeys("testPassword");
driver.findElement(By.id("u_0_b")).click();.
Take a look at the following example or watch this ~2 min no voice video tutorial for end-to-end execution. 
idDemo.java
package selenium.locators.examples;

importjava.util.concurrent.TimeUnit;

importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.chrome.ChromeDriver;

//id demo
publicclassidDemo{

publicstaticvoidmain(String[] args){

WebDriver driver
;

System
.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");
System
.setProperty("webdriver.chrome.silentOutput","true");

//chrome driver object
driver
=new ChromeDriver();

driver
.get("https://www.facebook.com");

//maximizing the URL
driver
.manage().window().maximize();

//finding email element by "id" locator and entering email
driver
.findElement(By.id("email")).sendKeys("test123@gmail.com");

//finding pass element by "id" locator and entering password
driver
.findElement(By.id("pass")).sendKeys("testPassword");

//finding "Login" element by "id" locator and performing click action
driver
.findElement(By.id("u_0_b")).click();

//driver.manage().timeouts().implicitlyWait(20000, TimeUnit.SECONDS);

//driver.quit();

}
}

- Sadakar Pochampalli

Locators for selenium | name locator example | gmail login automation example in java-selenium

$
0
0
Hi,

In this post, you will see the demonstration of "name" locator usage. 

"name" is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action(s).

For instance, Login to gmail  @ https://mail.google.com/
Let's see how to identify the name locators of login elements for gmail web application.

Email or Phone input text input HTML with "name" locator 
<inputtype="email"class="whsOnd zHQkBf"jsname="YPqjbf"
       autocomplete="username"spellcheck="false"tabindex="0"
       aria-label="Email or phone"name="identifier"value=""autocapitalize="none"
       id="identifierId"dir="ltr"data-initial-dir="ltr"data-initial-value="">

Enter your password text input HTML with "name" locator
<inputtype="password"class="whsOnd zHQkBf"jsname="YPqjbf"
       autocomplete="current-password"spellcheck="false"tabindex="0"
       aria-label="Enter your password"name="password"autocapitalize="off"
       dir="ltr"data-initial-dir="ltr"data-initial-value="">

Click on the image to get best view

selenium identifies the above input elements(username and password for gmail) using "name" locator with the following java statements. 
driver.findElement(By.name("identifier")).sendKeys("java.selenium2021@gmail.com");

WebElement elePassword=driver.findElement(By.name("password"));
elePassword
.sendKeys("JavaSelenium2021");
Take a look at the following example or watch this 1 min no voice video tutorial for end-to-end demo understanding and execution. 
nameLocatorDemo.java
//name locator demo
package selenium.locators.examples;

importjava.util.concurrent.TimeUnit;
importorg.openqa.selenium.By;
importorg.openqa.selenium.Keys;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.chrome.ChromeDriver;

publicclassnameLocatorDemo{

publicstaticvoidmain(String[] args){

WebDriver driver
;

System
.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");
System
.setProperty("webdriver.chrome.silentOutput","true");

driver
=new ChromeDriver();
driver
.navigate().to("https://mail.google.com/");

driver
.manage().window().maximize();

// locate "Email or Phone" text input with "name" locator and enter email say --> java.selenium2021@gmail.com

driver.findElement(By.name("identifier")).sendKeys("java.selenium2021@gmail.com");

// click on "Next" button - This is an xpath example that will be covered in later sessions
driver
.findElement(By.xpath("//span[@class='RveJvd snByac']")).click();

driver
.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//locate "Enter your password" text input with "password" locator and enter password say --> JavaSelenium2021
WebElement elePassword=driver.findElement(By.name("password"));
elePassword.sendKeys("JavaSelenium2021");


elePassword
.sendKeys(Keys.TAB);
elePassword
.sendKeys(Keys.TAB);

// click on "Next" button - This is again an xpath example.
driver
.findElement(By.xpath("//span[contains(text(),'Next')]")).click();

//close the driver
//driver.close();
}
}


- Sadakar Pochampalli

Locators for selenium | className locator example | gmail login automation example in java-selenium

$
0
0
Hi,

In this post, you will see demonstration of "className" locator usage. 

"classname" is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action(s).

For instance, Login to gmail  @ https://mail.google.com/
Let's see how to identify the name locators of login elements for gmail web application.

Email or Phone input text input HTML with "name" locator 
<inputtype="email"class="whsOnd zHQkBf"jsname="YPqjbf"autocomplete="username"spellcheck="false"tabindex="0"aria-label="Email or phone"name="identifier"value=""autocapitalize="none"id="identifierId"dir="ltr"data-initial-dir="ltr"data-initial-value=""badinput="false"aria-invalid="false"xpath="1">

selenium identifies the above input element(Email or Phone) using "className" locator with the following java statement. 
driver.findElement(By.className("whsOnd")).sendKeys("java.selenium2021@gmail.com");

Tap on the image to get better visibility: 
To avoid StaleElementReferenceException for other elements locators having the same class name ,  I am taking xpaths to find them, for instance , password has the same className i.e., class="whsOnd zHQkBf"  so instead of having className for password taking xpath //input[@name='password']


classNameLocatorDemo.java
package selenium.locators.examples;

importjava.util.concurrent.TimeUnit;
importorg.openqa.selenium.By;
importorg.openqa.selenium.Keys;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.chrome.ChromeDriver;

publicclassclassNameLocatorDemo{

publicstaticvoidmain(String[] args){

WebDriver driver
;

System
.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");
System
.setProperty("webdriver.chrome.silentOutput","true");

driver
=new ChromeDriver();

driver
.navigate().to("https://mail.google.com/");
driver
.manage().window().maximize();

//finding "Email or Phone" input text by clasName locator and enter value
driver
.findElement(By.className("whsOnd")).sendKeys("java.selenium2021@gmail.com");

// click on "Next" button - This is an xpath example that will be covered in later sessions
driver
.findElement(By.xpath("//span[@class='RveJvd snByac']")).click();

driver
.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// locate "Enter your password" text input with xpath locator and enter password say --> JavaSelenium2021
// If we take className for this input we will end up with
// Exception in thread "main" org.openqa.selenium.StaleElementReferenceException:
// stale element reference: element is not attached to the page document

WebElement elePassword
=driver.findElement(By.xpath("//input[@name='password']"));
elePassword
.sendKeys("JavaSelenium2021");

elePassword
.sendKeys(Keys.TAB);
elePassword
.sendKeys(Keys.TAB);

// click on "Next" button - This is again an xpath example.
driver
.findElement(By.xpath("//span[contains(text(),'Next')]")).click();

//close the driver
//driver.close();
}
}



Locators for selenium | tagName locator example | display anchor tag "a" texts and images alternative texts for amazon india website using java-selenium

$
0
0
Hi,

In this post, you will see demonstration of "tagName" locator usage. 

"tagName"  is one of the 8 locators supported by selenium.

For instance, display all the anchors "a" or "images" alternative texts on amazaon india page   @ https://www.amazon.in/

selenium identifies the "a" and "image" tags with the following java statements.

List<WebElement> links = driver.findElements(By.tagName("a"));
List<WebElement> images = driver.findElements(By.tagName("img"));

tagNameLocatorDemo.java
package selenium.locators.examples;
importjava.util.List;

importorg.openqa.selenium.By;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.chrome.ChromeDriver;

publicclasstagNameLocatorDemo{

publicstaticvoidmain(String[] args){

WebDriver driver
;

System
.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");
System
.setProperty("webdriver.chrome.silentOutput","true");

driver
=new ChromeDriver();

driver
.navigate().to("https://www.amazon.in/");
driver
.manage().window().maximize();

// storing anchor - a tags in links List<WebElement> variable
List
<WebElement> links = driver.findElements(By.tagName("a"));

// printing the size of list
System
.out.println("Size of list="+links.size());

// print the top 5 Text of anchors
System
.out.println("-- Printing top 5 anchors text--");
for(int i=0;i<links.size();i++){
System
.out.println(links.get(i).getText());
if(i==4)
break;
}
System
.out.println("------------------------------------");

// storing images - img tags in images List<WebElement> variable
List
<WebElement> images = driver.findElements(By.tagName("img"));

// foreach loop with WebElements
// if wants to break the loop on a particular index go with regular loop
System
.out.println("-- Printing images alternative texts --");
for(WebElement w2 : images){
System
.out.println(w2.getAttribute("alt"));
}

}
}

Watch this ~ 1.5 min video for end-to-end example execution



WebElement interface methods examples in selenium | Understanding of methods getText(), sendKeys(), clear(), getAttribute() and click() for radio button and check box

$
0
0
Hi , In this post - I'm writing my learning experiences on various methods of "WebElement" interface.
Test site courtesy : 

Watch the below ~1 min video for end-to-end execution 
getText()
  • getText() method gets you the visible text or inner text of an element. 
  • That is it fetches text between the opening and closing tags. 
  • For instance, the following text between bold tags can be fetched using getText() method.
    <bxpath="1">This is sample text.</b>
  • Store the locator in a Weblement variable and then use getText()
    //getText() example --> locate text "This is sample text." on page and display the text
    WebElement ThisIsSimpleText
    = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
    String displayThisIsSimpleText
    = ThisIsSimpleText.getText();
    System
    .out.println(displayThisIsSimpleText);
sendKeys()
  • This method allows users to enter data into editable elements such as text boxes or search boxes.
  • For instance, first name is a text box input and using sendKeys() method enter input value
    <inputid="fname"type="text"name="firstName"xpath="1">
  • Code snippet
    //sendKeys("sadakar") example --> locate TextBox input and enter first name
    WebElement firstName
    = driver.findElement(By.xpath("//input[@id='fname']"));
    firstName
    .sendKeys("Sadakar");
clear()
  • clear() method clears any text already entered or displayed in text box or search box inputs. 
  • Some applications may use default values in editable forms so clear them before entering new.
  • For instance, clear the already existing text in "first name" text box and enter new value
    //clear() --> clear TextBox input and re-enter first name
    firstName
    .clear();
    firstName
    .sendKeys("Hasini");
getAttribute("<attribute>")
  • getAttribute() method returns the current value of a given attribute as a string.
    <inputid="fname"type="text"name="firstName"xpath="1">
  • id, type, name , xpath and vlaue(not given above statement) are attributes of first name element HTML 
  • For instance, the following snippet for firstname text field fetches the value displayed on the form then the values of the corresponding attributes
    //getAttribute("<attribute>") --> <input id="fname" type="text" name="firstName">
    firstName
    .getAttribute("value");
    System
    .out.println("<input id=\"fname\" type=\"text\" name=\"firstName\">");
    System
    .out.println("Value of value attribute="+firstName.getAttribute("value"));
    System
    .out.println("Value of id attribute="+firstName.getAttribute("id"));
    System
    .out.println("Value of type attribute="+firstName.getAttribute("type"));
    System
    .out.println("Value of name attribute="+firstName.getAttribute("name"));
Handling radio buttons and check boxes using - click() method
  • Toggling(select or deselect) on/off are the actions performed for radio buttons or check boxes. 
  • Using click() method toggling can be done. 
  • For instance, take a look at the following code snippet - "male" radio button and check boxes for testings labels are selected.
    //radio button click example --> locate "male" radio button and select it
    WebElement male
    = driver.findElement(By.xpath("//input[@id='male']"));
    male
    .click();

    //check box click example - locate "Automation Testing" check box and tick it
    WebElement automationTesting
    = driver.findElement(By.xpath("//input[@class='Automation']"));
    automationTesting
    .click();

    //check box click example - locate "Performance Testing" check box and tick it
    WebElement performanceTesting
    = driver.findElement(By.xpath("//input[@class='Performance']"));
    performanceTesting
    .click();

Complete java class for above examples: WebElementInterfaceMethodsDemo.java
package selenium.webelement.methods;

importjava.util.concurrent.TimeUnit;

importorg.openqa.selenium.By;
importorg.openqa.selenium.PageLoadStrategy;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.chrome.ChromeDriver;
importorg.openqa.selenium.chrome.ChromeDriverService;
importorg.openqa.selenium.chrome.ChromeOptions;

publicclassWebElementInterfaceMethodsDemo{

publicstaticvoidmain(String[] args){

WebDriver driver
;

//loading Chrome driver from physical drive
System
.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");

System
.setProperty("webdriver.chrome.silentOutput","true");
//System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");

//launch the browser
driver
=new ChromeDriver();

//navigate to site
driver
.navigate().to("https://www.testandquiz.com/selenium/testing.html");

//maximize the browser
driver
.manage().window().maximize();

//getText() example --> locate text "This is sample text." on page and display the text
WebElement ThisIsSimpleText
= driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
String displayThisIsSimpleText
= ThisIsSimpleText.getText();
System
.out.println(displayThisIsSimpleText);

//sendKeys("sadakar") example --> locate TextBox input and enter first name
WebElement firstName
= driver.findElement(By.xpath("//input[@id='fname']"));
firstName
.sendKeys("Sadakar");

//clear() --> clear TextBox input and re-enter first name
firstName
.clear();
firstName
.sendKeys("Hasini");

//getAttribute("<attribute>") --> <input id="fname" type="text" name="firstName">
firstName
.getAttribute("value");
System
.out.println("<input id=\"fname\" type=\"text\" name=\"firstName\">");
System
.out.println("Value of value attribute="+firstName.getAttribute("value"));
System
.out.println("Value of id attribute="+firstName.getAttribute("id"));
System
.out.println("Value of type attribute="+firstName.getAttribute("type"));
System
.out.println("Value of name attribute="+firstName.getAttribute("name"));

//radio button click example --> locate "male" radio button and select it
WebElement male
= driver.findElement(By.xpath("//input[@id='male']"));
male
.click();

//check box click example - locate "Automation Testing" check box and tick it
WebElement automationTesting
= driver.findElement(By.xpath("//input[@class='Automation']"));
automationTesting
.click();

WebElement performanceTesting
= driver.findElement(By.xpath("//input[@class='Performance']"));
performanceTesting
.click();

//close the browser
driver
.close();

//close all the browsers opened by WebDriver during execution and quit the session
driver
.quit();
}
}

Locators for selenium | xpath locator example | gmail login automation example in java-selenium

$
0
0

XPath
  • XPath = XML Path
  • It is a type of query language to identify any element on the web page. 
  • Syntax
    //tagname[@attribute='value']
  • Writing XPath for complex applications sometimes cumbersome task.
  • There are plenty of plug-ins available for chrome to find Xpaths and one such tool is  "Chropath" pulg-in. 
  • Take a look at the below image to find relative XPath for "Email or Phone" text input.
    Tap on the image to get better visibility of  content
    Let's understand with an example, Identify gmail's  "Email or phone" text input with xpath
    Tap on the image to get better visibility:

    HTML
    <inputtype="email"class="whsOnd zHQkBf"jsname="YPqjbf"autocomplete="username"spellcheck="false"tabindex="0"aria-label="Email or phone"name="identifier"value=""autocapitalize="none"id="identifierId"dir="ltr"data-initial-dir="ltr"data-initial-value="">

    from the above HTML,  tagname is input  | type is an attribute  | value is email

    Xpath to locate the "Email or phone" is
    //input[@type='email']

    Java-selenium identifies the element with the following xpath locator
    driver.findElement(By.xpath("//input[@id='identifierId']"))

    Watch this ~4 min video tutorial example for automating gmail login process in which use xpath locators for "Email or Phone" or "Password"  or "Next" buttons. 


    java-selenium code to identify gmail login using xpath locators
    xpathLocatorGmailLoginDemo.java
    //x-path locator example

    package selenium.locators.examples;
    importjava.util.concurrent.TimeUnit;
    importorg.openqa.selenium.By;
    importorg.openqa.selenium.Keys;
    importorg.openqa.selenium.WebDriver;
    importorg.openqa.selenium.WebElement;
    importorg.openqa.selenium.chrome.ChromeDriver;

    publicclassxpathLocatorGmailLoginDemo{

    publicstaticvoidmain(String[] args){

    WebDriver driver
    ;

    System
    .setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");
    System
    .setProperty("webdriver.chrome.silentOutput","true");

    driver
    =new ChromeDriver();
    driver
    .manage().window().maximize();

    driver
    .navigate().to("https://mail.google.com/");

    //locate "Email or Phone" text box input using "xpath" and enter email
    driver
    .findElement(By.xpath("//input[@id='identifierId']")).sendKeys("java.selenium2021@gmail.com");

    // locate "Next" button and click
    driver
    .findElement(By.xpath("//span[@class='RveJvd snByac']")).click();

    driver
    .manage().timeouts().implicitlyWait(3000, TimeUnit.SECONDS);

    //locate "Enter your password" text box input using "xpath" and enter password
    WebElement elePassword
    =driver.findElement(By.xpath("//input[@name='password']"));
    elePassword
    .sendKeys("JavaSelenium2021");

    elePassword
    .sendKeys(Keys.TAB);
    elePassword
    .sendKeys(Keys.TAB);

    // locate "Next" button and click
    driver
    .findElement(By.xpath("//span[contains(text(),'Next')]")).click();

    //driver.close();
    }
    }

    WebElement interface methods examples in selenium - part 2 | Understanding of methods isDisplayed() Vs isEnabled() Vs isSelected()

    $
    0
    0
    Hi, In this post, we will see the differences between WebElement interface most commonly used methods - isDisplayed(), isEnabled() and isSelected() with real time example scenarios.

    IsEnabled() has some special purpose of verifying elements such as buttons enabled or disabled status. Let's look into each of them.

    Image and test site courtesy : https://www.testandquiz.com/selenium/testing.html

    isDisplayed() 
    • To verify presence of a web-element with in the web page. 
    • This method returns either true or false boolean values. 
    • If the element is present it returns "true" otherwise it returns "false". 
    • This method avoids the problem of having to parse an element's "style" attribute.
    • This method can be applicable for almost all of the elements on web-page.
    Example:  
    HTML for : Sample
    <bxpath="1">This is sample text.</b>

    Selenium snippet
    //isDisplayed() | Text on web page | Example : This is sample text.
    WebElement ThisIsSimpleText
    = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
    boolean b1 = ThisIsSimpleText.isDisplayed();
    System
    .out.println("Verify dispaly status of the text \"This is sample Text\"="+b1);

    isEnabled()

    • To verify if an element is enabled or disabled on web-page. 
    • Returns "ture" if element is enabled and returns "false" if an element is disabled. 
    • Examples: Mostly used with button elements, locked/disabled text input elements. 
    Example :
    Please find this blog post for a real time login use case example in which you will see "Sign Up" button is enabled after selecting a check box of terms and conditions.
      isSelected() 
      • Returns whether an element say check box or radio button is selected or not. 
      • If selected returns "true", if not selected returns "false". 
      • Examples: Check boxes, drop downs , radio buttons
      Example:
      HTML
      <inputid="male"type="radio"name="gender"value="male"xpath="1">
        Selenium snippet
        //isSelected()  | Example :  male radio button
        WebElement maleRaditoButton
        = driver.findElement(By.xpath("//input[@id='male']"));
        boolean b2 = maleRaditoButton.isSelected(); //false
        System
        .out.println("Verify male radio button selected or not before click = "+b2);
        //select the male radio button and verify isSelected()
        maleRaditoButton
        .click();
        boolean b3 = maleRaditoButton.isSelected(); //true
        System
        .out.println("Verify male radio button selected or not after click = "+b3);

        Checkout this video tutorial to understand the example below

        WebElementInterfaceMethods_isDisplayedisSelectedDemo.java
        package selenium.webelement.methods;

        /* isDisplayed() , and isSelected() */

        importjava.util.concurrent.TimeUnit;

        importorg.openqa.selenium.By;
        importorg.openqa.selenium.PageLoadStrategy;
        importorg.openqa.selenium.WebDriver;
        importorg.openqa.selenium.WebElement;
        importorg.openqa.selenium.chrome.ChromeDriver;
        importorg.openqa.selenium.chrome.ChromeDriverService;
        importorg.openqa.selenium.chrome.ChromeOptions;

        publicclassWebElementInterfaceMethods_isDisplayedisSelectedDemo{

        publicstaticvoidmain(String[] args){

        WebDriver driver
        ;

        //loading Chrome driver from physical drive
        System
        .setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");

        System
        .setProperty("webdriver.chrome.silentOutput","true");
        //System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");

        //launch the browser
        driver
        =new ChromeDriver();

        //navigate to site
        driver
        .navigate().to("https://www.testandquiz.com/selenium/testing.html");

        //maximize the browser
        driver
        .manage().window().maximize();

        //isDisplayed() | Text on web page | Example : This is sample text.
        WebElement ThisIsSimpleText
        = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
        boolean b1 = ThisIsSimpleText.isDisplayed();
        System
        .out.println("Verify dispaly status of the text \"This is sample Text\"="+b1);

        //isSelected() | Example : male radio button
        WebElement maleRaditoButton
        = driver.findElement(By.xpath("//input[@id='male']"));
        boolean b2 = maleRaditoButton.isSelected();
        System
        .out.println("Verify male radio button selected or not before click = "+b2);

        //select the male radio button and verify isSelected()
        maleRaditoButton
        .click();
        boolean b3 = maleRaditoButton.isSelected();
        System
        .out.println("Verify male radio button selected or not after click = "+b3);


        //close the browser
        driver
        .close();

        //close all the browsers opened by WebDriver during execution and quit the session
        driver
        .quit();
        }
        }


        actions drag and drop elements

        Actions(class) and Action(interface) in selenium | demonstration of keyboard events in selenium | using keyboard events send capital letters to search this article in

        Jaspersoft reports server valid login and invalid login automation tutorial using Java-Selenium-Cucumber

        $
        0
        0
        Hi ,

        This is an introductory article on automating the Jaspersoft reports server user activities. In this tutorial, you would learn how to effectively implement cucumber framework with java selenium for Jaspersoft server.

        NOTE : 
        1) Assuming, the reader should already have basic knowledge on all the software's or technologies mentioned below.

        Software's used: 
        1) Eclipse - Version: 2.3.0.v20191210-0610, Build id: I20191210-0610
        2) Java 1.8
        3) Maven build tool (default comes with Eclipse)
        4) Cucumber 1.2.5
        5) Cucumber Junit 1.2.5
        6) Junit 4.12
        7) Log4j 1.2.17
        8) Google Chrome Browser : Version 80.0.3987.132 (Official Build) (64-bit)
        9) Jaspersoft 7.5 Community Server

        Automation flow architecture: 

        Click on the image to view in non-scroll mode or to view the whole flow:




        Note that you may have to download and point to correct chromedriver.exe driver. This demonstration is used chrome driver 80 versioned driver.

        To get a copy of this demo, drop me a message at
        LinkedIn


        Video tutorial : Execution flow of the project
        TBD

        Steps: 
        1) Creating a new Maven project

               File -> New -> Project -> Maven -> Maven Project
                 (Jaspersoft Automation is the project  name)

        2) Addlog4j library to the project build path.
             
        3) Ensure installed JRE points to locally installed jdk as shown in below image. 
            i.e., C:\Program Files\Java\jdk1.8.0_181


        4)  Thefinal project folder structure is as follows.

        5) pom.xml

        This will download and install the required libraries for the project. 

        <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
          <groupId>SMAPI_UI_POC</groupId>
          <artifactId>SMAPI_UI_POC</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <name>SMAPI_UI_POC</name>
          <description>SMAPI_UI_POC</description>
          <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
          </properties>
          <dependencies>

          <!--  cucumber-java -->
        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
        </dependency>

          <!--  cucumber-junit -->
        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->

        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!--
        <dependency>
                <groupId>io.cucumber</groupId>
                <artifactId>cucumber-junit</artifactId>
                <version>3.0.2</version>
                <scope>test</scope>
            </dependency>
        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
          </dependencies>

         <build>
        <pluginManagement>
        <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.21.0</version>
        </plugin>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        </plugin>
        </plugins>
        </pluginManagement>
        </build>
        </project>

        6) configuration.properties

        Read values from properties file 

        chrome_driver_path=D:\\chromedriver_80\\chromedriver.exe
        jaspersoft_server_url=http://localhost:8080/jasperserver
        user_id=jasperadmin
        password=jasperadmin

        7) 001_LoginJaspersoftServer.feature 

        Cucumber feature file with valid and invalid login scenarios using Scenario Outline concept.
        This code of language is called as Gherkin 

        #Author: sadakar.pochampalli
        # https://docs.katalon.com/katalon-studio/docs/cucumber-features-file.html#maintain-features-file
        # https://riptutorial.com/cucumber/example/28790/scenario-outline
        #https://www.tutorialspoint.com/cucumber/cucumber_scenario_outline.htm
        @Login
        Feature: Login feature

          As a admin user, I want to login to Jaspersoft Server so that
          I can run the reports, dashboards, create ad-hoc reports and etc.

          @ValidLogin
          Scenario Outline: Login with valid credentials
            Given Chrome browser and Jaspersoft login page
            When I enter User Id as "<UserId>" and Password as "<Password>"
            And I click on Login button
            Then I should be able to login successfully

            Examples:
              | UserId      | Password    |
              | jasperadmin | jasperadmin |
              | joeuser     | joeuser     |

          @InvalidLogin
          Scenario Outline: Login with Invalid credentials
            Given Chrome browser and Jaspersoft login page
            When I enter User Id as "<UserId>" and Password as "<Password>"
            And I click on Login button
            Then I should NOT be able to login successfully

            Examples:
              | UserId  | Password    |
              | baduser | jasperadmin |
              | joeuser | badpassword |
              | baduser | badpassword |

        8) log4j.properties

        DEBUG, ERROR, INFO logs displayed in file at : D:\\jasper_selenium\\jasper_selenium.logs

        # Root logger option
        log4j.rootLogger=DEBUG,stdout,dest1,ERROR,INFO

        # Direct log messages to a log file
        log4j.appender.dest1=org.apache.log4j.RollingFileAppender
        log4j.appender.dest1.File=D:\\jasper_selenium\\jasper_selenium.logs
        log4j.appender.dest1.MaxFileSize=10MB
        log4j.appender.dest1.MaxBackupIndex=10
        log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
        log4j.appender.dest1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
        log4j.appender.dest1.Append=false

        # Direct log messages to stdout
        log4j.appender.stdout=org.apache.log4j.ConsoleAppender
        log4j.appender.stdout.Target=System.out
        log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
        log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

        #ERROR
        log4j.appender.ERROR=org.apache.log4j.RollingFileAppender
        log4j.appender.ERROR.layout=org.apache.log4j.PatternLayout
        log4j.appender.ERROR.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
        #log4j.appender.ERROR.File=D:\\smapiui_logs\\smapi_ui.logs

        #INFO
        log4j.appender.INFO=org.apache.log4j.RollingFileAppender
        log4j.appender.INFO.layout=org.apache.log4j.PatternLayout
        log4j.appender.INFO.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
        #log4j.appender.INFO.File=D:\\smapiui_logs\\smapi_ui.logs

        9) Hooks.java - This class displays each scenario name with it's status. 

        package com.sadakar.cucumber.common;
        import com.sadakar.resource.utilities.Log;
        import cucumber.api.Scenario;
        import cucumber.api.java.After;
        import cucumber.api.java.Before;

        public class Hooks {
        @Before(order=0)
        public void before(Scenario scenario) {
            System.out.println("------------------------------");
            Log.info("------------------------------");
            Log.info("Scenario: '" + scenario.getName() );
            Log.info("******************************");
            System.out.println("Starting - " + scenario.getName());
            System.out.println("------------------------------");
        }
        @After(order=0)
        public void after(Scenario scenario) {
            System.out.println("------------------------------");
            Log.info("Scenario: '" + scenario.getName() + "' has status " + scenario.getStatus());
            Log.info("******************************");
            Log.info("------------------------------");
            System.out.println(scenario.getName() + " Status - " + scenario.getStatus());
            System.out.println("------------------------------");
        }
        }

        10) CucumberRunner.java

        In this class, give path for the features, glue code, which scenarios to test/run and cucumber plugins such as reports in various formats

        package com.sadakar.cucumber.runner;
        import org.junit.runner.RunWith;
        import cucumber.api.CucumberOptions;
        import cucumber.api.junit.Cucumber;

        @RunWith(Cucumber.class)
        @CucumberOptions
        (
        features="classpath:features",
        tags="@ValidLogin,@InvalidLogin",
        glue={"com.sadakar.cucumber.stepdefinitions/","com.sadakar.cucumber.common"},
        plugin = { "pretty", "json:target/cucumber-reports/Cucumber.json",
        "junit:target/cucumber-reports/Cucumber.xml",
        "html:target/cucumber-reports"},
        monochrome = true
        )
        public class CucumberRunner {

        }

        11) LoginToJaspersoft.java

        In this class define the step definitions for the scenarios. This code is called glue code. Wherever required, add the wait, sleep statements based on the logon speed of your jaspersoft server. 

        package com.sadakar.cucumber.stepdefinitions;

        import com.sadakar.resource.utilities.Log;
        import com.sadakar.selenium.common.BasePage;
        import com.sadakar.selenium.common.CommonFunctions;
        import cucumber.api.java.en.And;
        import cucumber.api.java.en.Given;
        import cucumber.api.java.en.Then;
        import cucumber.api.java.en.When;
        import java.util.concurrent.TimeUnit;
        import org.junit.Assert;
        import org.openqa.selenium.By;
        import org.openqa.selenium.Keys;

        public class LoginToJaspersoft extends BasePage{
        CommonFunctions cf = new CommonFunctions();
        @Given("^Chrome browser and Jaspersoft login page$")
        public void chrome_browser_and_Jaspersoft_login_page() throws Throwable {
        try {   
        cf.initDriver();
        cf.maximizeDriver();
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        cf.getJapsersoftURL();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        }
        catch(Exception e) {
        Log.error("failed to open the Japsersoft URL or Login page"+e);
        Assert.fail("failed to open the Japsersoft URL or Login page"+e);
        }
        }

        @When("^I enter User Id as \"([^\"]*)\" and Password as \"([^\"]*)\"$")
        public void i_enter_User_Id_as_and_Password_as(String arg1, String arg2) throws Throwable {
          Log.debug("Enter User Id");
          driver.findElement(By.xpath("//*[@id='j_username']")).sendKeys(arg1+Keys.TAB);
          Log.debug("Enter tab");
          Log.debug("Enter Password");
              driver.findElement(By.xpath("//*[@id='j_password_pseudo']")).sendKeys(arg2+Keys.TAB);
              Log.debug("Enter tab");
        }
        @And("^I click on Login button$")
        public void i_click_on_Login_button() throws Throwable {
        Log.debug("Click Login button");
              driver.findElement(By.xpath("//*[@id='submitButton']")).click();  
              Thread.sleep(5000);
        }

        @Then("^I should be able to login successfully$")
        public void i_should_be_able_to_login_successfully() throws Throwable {
        if(driver.getCurrentUrl().equalsIgnoreCase(
              "http://localhost:8080/jasperserver/flow.html?_flowId=searchFlow")){
                 Log.debug("Login Successfull");
              } else { 
                 Log.debug("Login NOT Success full");
                 Assert.fail("Login NOT Success full");
              } 
        driver.close(); 
        driver.quit();
        }
        @Then("^I should NOT be able to login successfully$")
        public void i_should_NOT_be_able_to_login_successfully() throws Throwable {
        if(driver.getCurrentUrl().equalsIgnoreCase(
              "http://localhost:8080/jasperserver/login.html?error=1")){
                 Log.debug("Invalid Login Successfull");
              } else { 
                 Log.debug("Invalid Login NOT Success full");
                 Assert.fail("Invalid Login NOT Success full");
              } 
        driver.close(); 
        driver.quit();
        }
        }

        12) Log.java

        package com.sadakar.resource.utilities;
        import org.apache.log4j.Logger;
        public class Log {

        public static Logger log= Logger.getLogger(Log.class.getSimpleName());
        //Logger log2 = Logger.getLogger("devpinoyLogger");

        /**
        * To print Log for the start test case
        * @param startTestCaseMessage
        */
        public static void startTestCase(String startTestScenario ) {
        log.info("********************* " + "S_T_A_R_T" + " *********************");
        log.info("********************* " + startTestScenario + " *********************");
        }

        /**
        * This is to print Log for the ending of the test case
        * @param endTestCaseMessage
        */
        public static void endTestCase(String endTestScenario) {
        log.info("********************* " + "-E---N---D-" + " *********************");
        log.info("********************* " + endTestScenario + " *********************");
        }

        public static void info(String infoMessage) {
        log.info(infoMessage);
        }

        public static void warn(String warnMessage) {
        log.warn(warnMessage);
        }

        public static void error(String errorMessage) {
        log.error(errorMessage);
        }

        public static void fatal(String fatalMessage) {
        log.fatal(fatalMessage);
        }

        public static void debug(String debugMessage) {
        log.debug(debugMessage);
        }

        }

        13) PropertyManager.java

        package com.sadakar.resource.utilities;
        import java.io.FileInputStream;
        import java.io.IOException;
        import java.util.Properties;
        public class PropertyManager {
        private static PropertyManager instance;
            private static final Object lock = new Object();
            private static String propertyFilePath=System.getProperty("user.dir") + "\\configuration.properties";    
            private static String jaspersoft_server_url;
            private static String chrome_driver_path;
            private static String user_id;
            private static String password;
            
            //Create a Singleton instance. We need only one instance of Property Manager.
            public static PropertyManager getInstance () {
                if (instance == null) {
                    synchronized (lock) {
                        instance = new PropertyManager();
                        instance.loadData();
                    }
                }
                return instance;
            }
            //Get all configuration data and assign to related fields.
            private void loadData() {
                //Declare a properties object
                Properties prop = new Properties();
                //Read configuration.properties file
                try {
                    prop.load(new FileInputStream(propertyFilePath));
                    //prop.load(this.getClass().getClassLoader().getResourceAsStream("configuration.properties"));
                } catch (IOException e) {
                    System.out.println("Configuration properties file cannot be found");
                }
                //Get properties from configuration.properties
                jaspersoft_server_url = prop.getProperty("jaspersoft_server_url");
                chrome_driver_path=prop.getProperty("chrome_driver_path");
                user_id=prop.getProperty("user_id");
                password=prop.getProperty("password");

            }
            public String getAppMangtURL () {
              return jaspersoft_server_url;
            }
            public String getChormeDriverPath () {
                return chrome_driver_path;
              }
            
            public String getUserId () {
                return user_id;
              }
              public String getPassword () {
                  return password;
                }
        }

        14) Basepage.java

        package com.sadakar.selenium.common;
        import org.openqa.selenium.WebDriver;

        public class BasePage {
        public  static WebDriver driver;
        public static void main(String args[]){
        }

        }

        15) CommonFunctions.java

        package com.sadakar.selenium.common;
        import org.openqa.selenium.chrome.ChromeDriver;
        import org.openqa.selenium.chrome.ChromeOptions;
        import com.sadakar.resource.utilities.Log;
        import com.sadakar.resource.utilities.PropertyManager;

        import org.openqa.selenium.PageLoadStrategy;
        public class CommonFunctions extends BasePage{
        String chromeDriverPath=PropertyManager.getInstance().getChormeDriverPath();
        String appMangtURL = PropertyManager.getInstance().getAppMangtURL();

        public void initDriver() {
        Log.debug("finding chrome driver path");
        System.setProperty("webdriver.chrome.driver",chromeDriverPath);
        Log.debug("Chrome driver path found");
        Log.debug("Initiate Chrome driver");
        ChromeOptions options = new ChromeOptions();
                //options.addArguments("--headless");
                options.addArguments("--disable-gpu");
                options.setPageLoadStrategy(PageLoadStrategy.NONE);
                options.addArguments("--allow-insecure-localhost");
                options.addArguments("--allow-running-insecure-content");
                options.addArguments("--ignore-certificate-errors");
                options.addArguments("--no-sandbox");
                options.addArguments("--window-size=1280,1000");
                options.setCapability("acceptSslCerts", true);
                options.setCapability("acceptInsecureCerts", true);
                
        driver = new ChromeDriver(options);
        Log.debug("Chrome driver is being initiated");
        }
        public void maximizeDriver() {
        Log.debug("Maximize Chrome Browser");
        driver.manage().window().maximize();
        Log.debug("Chrome Browser maximized");
        }
        public void getJapsersoftURL() {
        Log.debug("Authenticating to Jaspersoft Reports Server");
        //System.out.println("App magt URL="+appMangtURL);
        //driver.get("http://management.myabilitynetwork.lab/");
                driver.get(appMangtURL);
                Log.debug("Enter User ID and Password");
        }
        public void closeDriver() {
        Log.debug("Closing driver: Closing browser");
        driver.close();
        Log.debug("Driver is closed: Closed browser");
        }
        public void quitDriver() {
        Log.debug("Closing driver session");
        driver.quit();
        Log.debug("Driver session is closed");
        }

        }

        16) Cucumber reports




        17) jasper_selenium.logs

        2020-03-13 19:22:57 INFO  Log:30 - ------------------------------
        2020-03-13 19:22:57 INFO  Log:30 - Scenario: 'Login with valid credentials
        2020-03-13 19:22:57 INFO  Log:30 - ******************************
        2020-03-13 19:22:57 DEBUG Log:46 - finding chrome driver path
        2020-03-13 19:22:57 DEBUG Log:46 - Chrome driver path found
        2020-03-13 19:22:57 DEBUG Log:46 - Initiate Chrome driver
        2020-03-13 19:23:07 DEBUG Log:46 - Chrome driver is being initiated
        2020-03-13 19:23:07 DEBUG Log:46 - Maximize Chrome Browser
        2020-03-13 19:23:07 DEBUG Log:46 - Chrome Browser maximized
        2020-03-13 19:23:07 DEBUG Log:46 - Authenticating to Jaspersoft Reports Server
        2020-03-13 19:23:07 DEBUG Log:46 - Enter User ID and Password
        2020-03-13 19:23:07 DEBUG Log:46 - Enter User Id
        2020-03-13 19:23:08 DEBUG Log:46 - Enter tab
        2020-03-13 19:23:08 DEBUG Log:46 - Enter Password
        2020-03-13 19:23:08 DEBUG Log:46 - Enter tab
        2020-03-13 19:23:08 DEBUG Log:46 - Click Login button
        2020-03-13 19:23:14 DEBUG Log:46 - Login Successfull
        2020-03-13 19:23:15 INFO  Log:30 - Scenario: 'Login with valid credentials' has status passed
        2020-03-13 19:23:15 INFO  Log:30 - ******************************
        2020-03-13 19:23:15 INFO  Log:30 - ------------------------------
        2020-03-13 19:23:15 INFO  Log:30 - ------------------------------
        2020-03-13 19:23:15 INFO  Log:30 - Scenario: 'Login with valid credentials
        2020-03-13 19:23:15 INFO  Log:30 - ******************************
        2020-03-13 19:23:15 DEBUG Log:46 - finding chrome driver path
        2020-03-13 19:23:15 DEBUG Log:46 - Chrome driver path found
        2020-03-13 19:23:15 DEBUG Log:46 - Initiate Chrome driver
        2020-03-13 19:23:24 DEBUG Log:46 - Chrome driver is being initiated
        2020-03-13 19:23:24 DEBUG Log:46 - Maximize Chrome Browser
        2020-03-13 19:23:24 DEBUG Log:46 - Chrome Browser maximized
        2020-03-13 19:23:24 DEBUG Log:46 - Authenticating to Jaspersoft Reports Server
        2020-03-13 19:23:24 DEBUG Log:46 - Enter User ID and Password
        2020-03-13 19:23:24 DEBUG Log:46 - Enter User Id
        2020-03-13 19:23:25 DEBUG Log:46 - Enter tab
        2020-03-13 19:23:25 DEBUG Log:46 - Enter Password
        2020-03-13 19:23:25 DEBUG Log:46 - Enter tab
        2020-03-13 19:23:25 DEBUG Log:46 - Click Login button
        2020-03-13 19:23:30 DEBUG Log:46 - Login Successfull
        2020-03-13 19:23:31 INFO  Log:30 - Scenario: 'Login with valid credentials' has status passed
        2020-03-13 19:23:31 INFO  Log:30 - ******************************
        2020-03-13 19:23:31 INFO  Log:30 - ------------------------------
        2020-03-13 19:23:31 INFO  Log:30 - ------------------------------
        2020-03-13 19:23:31 INFO  Log:30 - Scenario: 'Login with Invalid credentials
        2020-03-13 19:23:31 INFO  Log:30 - ******************************
        2020-03-13 19:23:31 DEBUG Log:46 - finding chrome driver path
        2020-03-13 19:23:31 DEBUG Log:46 - Chrome driver path found
        2020-03-13 19:23:31 DEBUG Log:46 - Initiate Chrome driver
        2020-03-13 19:23:40 DEBUG Log:46 - Chrome driver is being initiated
        2020-03-13 19:23:40 DEBUG Log:46 - Maximize Chrome Browser
        2020-03-13 19:23:41 DEBUG Log:46 - Chrome Browser maximized
        2020-03-13 19:23:41 DEBUG Log:46 - Authenticating to Jaspersoft Reports Server
        2020-03-13 19:23:41 DEBUG Log:46 - Enter User ID and Password
        2020-03-13 19:23:41 DEBUG Log:46 - Enter User Id
        2020-03-13 19:23:42 DEBUG Log:46 - Enter tab
        2020-03-13 19:23:42 DEBUG Log:46 - Enter Password
        2020-03-13 19:23:42 DEBUG Log:46 - Enter tab
        2020-03-13 19:23:42 DEBUG Log:46 - Click Login button
        2020-03-13 19:23:47 DEBUG Log:46 - Invalid Login Successfull
        2020-03-13 19:23:48 INFO  Log:30 - Scenario: 'Login with Invalid credentials' has status passed
        2020-03-13 19:23:48 INFO  Log:30 - ******************************
        2020-03-13 19:23:48 INFO  Log:30 - ------------------------------
        2020-03-13 19:23:48 INFO  Log:30 - ------------------------------
        2020-03-13 19:23:48 INFO  Log:30 - Scenario: 'Login with Invalid credentials
        2020-03-13 19:23:48 INFO  Log:30 - ******************************
        2020-03-13 19:23:48 DEBUG Log:46 - finding chrome driver path
        2020-03-13 19:23:48 DEBUG Log:46 - Chrome driver path found
        2020-03-13 19:23:48 DEBUG Log:46 - Initiate Chrome driver
        2020-03-13 19:23:57 DEBUG Log:46 - Chrome driver is being initiated
        2020-03-13 19:23:57 DEBUG Log:46 - Maximize Chrome Browser
        2020-03-13 19:23:57 DEBUG Log:46 - Chrome Browser maximized
        2020-03-13 19:23:57 DEBUG Log:46 - Authenticating to Jaspersoft Reports Server
        2020-03-13 19:23:57 DEBUG Log:46 - Enter User ID and Password
        2020-03-13 19:23:57 DEBUG Log:46 - Enter User Id
        2020-03-13 19:23:58 DEBUG Log:46 - Enter tab
        2020-03-13 19:23:58 DEBUG Log:46 - Enter Password
        2020-03-13 19:23:58 DEBUG Log:46 - Enter tab
        2020-03-13 19:23:58 DEBUG Log:46 - Click Login button
        2020-03-13 19:24:03 DEBUG Log:46 - Invalid Login Successfull
        2020-03-13 19:24:04 INFO  Log:30 - Scenario: 'Login with Invalid credentials' has status passed
        2020-03-13 19:24:04 INFO  Log:30 - ******************************
        2020-03-13 19:24:04 INFO  Log:30 - ------------------------------
        2020-03-13 19:24:04 INFO  Log:30 - ------------------------------
        2020-03-13 19:24:04 INFO  Log:30 - Scenario: 'Login with Invalid credentials
        2020-03-13 19:24:04 INFO  Log:30 - ******************************
        2020-03-13 19:24:04 DEBUG Log:46 - finding chrome driver path
        2020-03-13 19:24:04 DEBUG Log:46 - Chrome driver path found
        2020-03-13 19:24:04 DEBUG Log:46 - Initiate Chrome driver
        2020-03-13 19:24:14 DEBUG Log:46 - Chrome driver is being initiated
        2020-03-13 19:24:14 DEBUG Log:46 - Maximize Chrome Browser
        2020-03-13 19:24:14 DEBUG Log:46 - Chrome Browser maximized
        2020-03-13 19:24:14 DEBUG Log:46 - Authenticating to Jaspersoft Reports Server
        2020-03-13 19:24:14 DEBUG Log:46 - Enter User ID and Password
        2020-03-13 19:24:14 DEBUG Log:46 - Enter User Id
        2020-03-13 19:24:15 DEBUG Log:46 - Enter tab
        2020-03-13 19:24:15 DEBUG Log:46 - Enter Password
        2020-03-13 19:24:15 DEBUG Log:46 - Enter tab
        2020-03-13 19:24:15 DEBUG Log:46 - Click Login button
        2020-03-13 19:24:20 DEBUG Log:46 - Invalid Login Successfull
        2020-03-13 19:24:21 INFO  Log:30 - Scenario: 'Login with Invalid credentials' has status passed
        2020-03-13 19:24:21 INFO  Log:30 - ******************************
        2020-03-13 19:24:21 INFO  Log:30 - ------------------------------

        Handling internet explorer windows based authentication to a website using AutoIT script in java-cucumber-selenium automation

        $
        0
        0
        Hi,

        In this post, you will see tips on how to authenticate a website that is based on windows authentication. 
        Reader is assumed to have some prior fundamental knowledge on the java-selenium-cucumber framework/setup. 

        NOTE: 
        This post is not written to give step-by-step procedure instead written to give direct inputs on specific areas. 

        Sample cucumber feature file and scenario: 

        @feature_login
        Feature: Launch internet browser and login with valid credentials
          This is a windows based authentication for sadakar.selenium.com site using internet browser.

          @senario_loginsadakar.selenium.com
          Scenario: Login to sadakar.selenium.com with internet explorer windows based authentication
            When I open internet explorer browser
            Then I login with username and password and navigate to sadakar.selenium.com


        Problem statement : 
        When you try to open sadakar.selenium.com and if the website is configured for windows based authentication as shown in below image - how do you navigate to the site using java-selenium code ? 

        Click on the image to get best view of the content: 
        Solution : 
        1) Install latest Auto IT tool ( download : https://www.autoitscript.com/site/autoit/downloads/ )
        2) Then : 
                a) Open the website with its security pop-up for windows based authentication 
                b) Open the AutoIt tool on top of the the website's windows security pop-up. 
        3) Hold on "Finder Tool" on AutoIT and drag that on to the security pop-up window. 
        4) Note down "Title" and "Class" in the AutoIt tool. 

        Click on the image to get best view of the content: 


        5) Now, in Notepad++ file write below code and save it as "autoit_ie.au3"

        $sUsername = "SADA001\administrator"
        $sPassword = "SADAPassWord@001"
        $sTitle = WinGetTitle("Windows Security")
        Sleep(1000)
            If $sTitle = "Windows Security" or WinWaitActive("[CLASS:Credential Dialog Xaml Host]") or WinWaitActive("Windows Security") or WinWaitActive("iexplore.exe") or WinWaitActive("Connecting to sadakar.selenium.com")Then
                Send($sUsername)
                Send("{TAB}")
                Send($sPassword,1)
                Send("{TAB}")
                Send("{ENTER}")
            EndIf

        6) Right click on the saved file and compile it (just compile) and you would see "autoit_ie.exe" generated in the folder where you saved your au3 file. 

        NOTE : 
        if you try open this .exe, you would see some encrypted data that will not be readable. 

        7) How to call the generated autoit_ie.exe file in java-selenium. 

          public void getCredentialsFromAutoITExe() {
        try {
        Log.debug("Reading Username and Password from IE AutoIT exe file");
                                         System.out.println("Reading Username and Password from IE AutoIT exe file");
        Runtime.getRuntime().exec("D:\\autoit_ie.exe");
        Log.debug("Read Username and Password from AutoIT exe file");
        }
         
        }catch(Exception e) {
        Assert.fail("failed to Read Username and Password from AutoIT exe file");
        System.out.println("failed to read credentials from AutoIT exe file"+""+e);
        }
        }

         public void getAppManagementURL() {

        Log.debug("Authenticating to sadakar.selenium.com URL");
         driver.get("http://sadakar.selenium.com/");
                          Log.debug("Authenticated to Application URL and opened the site                             
                               http://sadakar.selenium.com/");
        }

        7) When you run your project (in my case its a maven-java-selenium-junit-cucumber) the pop-up should read the username and password from the auto_it.exe file and fill the corresponding values as shown in below image.

        NOTE : 
        Runtime.getRuntime().exec("auto it exe file path") should be called before driver.get("URL")


        Thank you, for stopping by and I hope it helps someone in the community. 

        WebElement interface methods examples in selenium - part 3 | Understanding of method isEnabled()

        $
        0
        0
        Hi, in this post, we will walk through the usage and live example of isEnabled() method. isEnabled() method, we apply in special scenarios where in we select a check box and get the status of a button i.e., enabled or disabled. Let's take a look into the following example.

        isEnabled()
        • To verify if an element is enabled or disabled on web-page. 
        • Returns "ture" if element is enabled and returns "false" if an element is disabled. 
        • Examples: Mostly used with button elements, locked/disabled text input elements.
        Problem Statement : 
        Display the status of "Sign up" button - The below two images gives an idea on how the button looks before enabled and after enabled after selecting a check box.

        Sign up  button before enabled i.e., before selecting check box "I have read...." 
        Tap on the image to get better visibility:
        Sign up  button after enabled i.e., after selecting check box "I have read...." 
        Tap on the image to get better visibility:
        The below piece of selenium script does
            a) verifies the status of "Sign up" button before enabled.
            b) selects the check box "I have read..." and
            c)  verifies the status of "Sign up" button after selecting the  check box.

        //isEnabled() example - before selecting the check box
        //display the enable or disable status of "Sign Up" button before selecting the check box
        WebElement signUp
        = driver.findElement(By.xpath("//button[@id='signup']"));
        boolean b1 = signUp.isEnabled();//false
        System
        .out.println("Sign Up button enable/disable before selecting \"I have read and accpet...\" check box = "+b1);


        //select the "I have read and accept check box
        WebElement element
        =driver.findElement(By.xpath("//input[@id='termsAndPrivacy']"));
        WebDriverWait wait
        =new WebDriverWait(driver,60);
        wait
        .until(ExpectedConditions.visibilityOf(element));
        newActions(driver).moveToElement(element,1,1).click().perform();

        //isEnabled() example - check box
        //display the enable or disable status of "Sign Up" button after selecting the check box
        boolean b2 = signUp.isEnabled();//true
        System
        .out.println("Sign Up button enable/disable after selecting \"I have read and accpet...\" check box = "+b2);

        WebElementInterfaceMethod_isEnabledDemo.java

        package selenium.webelement.methods;

        /* button isEnabled() demo */

        importorg.openqa.selenium.By;
        importorg.openqa.selenium.WebDriver;
        importorg.openqa.selenium.WebElement;
        importorg.openqa.selenium.chrome.ChromeDriver;
        importorg.openqa.selenium.interactions.Actions;
        importorg.openqa.selenium.support.ui.ExpectedConditions;
        importorg.openqa.selenium.support.ui.WebDriverWait;

        publicclassWebElementInterfaceMethod_isEnabledDemo{

        publicstaticvoidmain(String[] args){

        WebDriver driver;

        //loading Chrome driver from physical drive
        System.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");

        System.setProperty("webdriver.chrome.silentOutput","true");
        //System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");

        //launch the browser
        driver =new ChromeDriver();

        //navigate to site
        driver.navigate().to("https://us.megabus.com/account-management/login");

        //maximize the browser
        driver.manage().window().maximize();

        //close the message on site
        driver.findElement(By.xpath("//i[@class='close mb-close']")).click();

        // Sign Up form
        WebElement signUpFromTab = driver.findElement(By.xpath("//a[@class='btn btn-link btn-block'][contains(text(),'Sign up')]"));
        signUpFromTab.click();

        //Email
        WebElement email = driver.findElement(By.xpath("//input[@id='email']"));
        email.sendKeys("java.selenium2023@gmail.com");

        //Confirm Email
        WebElement confirmEmail = driver.findElement(By.xpath("//input[@id='confirmEmail']"));
        confirmEmail.sendKeys("java.selenium2023@gmail.com");

        //Choose a Password
        WebElement chooseAPassword = driver.findElement(By.xpath("//input[@id='choosePassword']"));
        chooseAPassword.sendKeys("JavaSelenium2023");

        //Confirm Password
        WebElement confirmPassword = driver.findElement(By.xpath("//input[@id='confirmPassword']"));
        confirmPassword.sendKeys("JavaSelenium2023");

        //isEnabled() example - before selecting the check box
        //display the enable or disable status of "Sign Up" button before selecting the check box
        WebElement signUp = driver.findElement(By.xpath("//button[@id='signup']"));
        boolean b1 = signUp.isEnabled();
        System.out.println("Sign Up button enable/disable before selecting \"I have read and accpet...\" check box = "+b1);


        //select the "I have read and accept check box
        WebElement element=driver.findElement(By.xpath("//input[@id='termsAndPrivacy']"));
        WebDriverWait wait =new WebDriverWait(driver,60);
        wait.until(ExpectedConditions.visibilityOf(element));
        newActions(driver).moveToElement(element,1,1).click().perform();

        //isEnabled() example - check box
        //display the enable or disable status of "Sign Up" button after selecting the check box
        boolean b2 = signUp.isEnabled();
        System.out.println("Sign Up button enable/disable after selecting \"I have read and accpet...\" check box = "+b2);

        signUp.click();

        //close the browser
        //driver.close();

        //close all the browsers opened by WebDriver during execution and quit the session
        //driver.quit();
        }
        }


        To know more about isDisplayed() or isSelected() methods, please visit this post @

        WebElement interface methods examples in selenium - part 2 | Understanding of methods isDisplayed() Vs isEnabled() Vs isSelected()


        isDisplayed()
        • To verify presence of a web-element with in the web page. 
        • This method returns either true or false boolean values. 
        • If the element is present it returns "true" otherwise it returns "false". 
        • This method avoids the problem of having to parse an element's "style" attribute.
        • Example : This method can be applicable for all the elements on web-page. 
         isSelected()
        • Returns whether an element say check box or radio button is selected or not. 
        • If selected returns "true", if not selected returns "false". 
        • Examples: Check boxes, drop downs , radio buttons 
        I hope this helps someone in the community, stay tuned for more automation.

          How to compare displayed row count on page is equals to data table row count in java-selenium ? | Calculate web data table row count in java-selenium

          $
          0
          0
          Hi , In this tutorial, we'll learn about how to compare displayed row count on page is equals to data table row count in java selenium.

          There are several ways to accomplish this, by the time I write this article, I've come across two ways.
          They are
          1) Calculate the no. of rows in data table by navigating through the pagination buttons.
          2) Calculate the no. of rows in data table by using jQuery "length" function.

          We will see the latter implementation in this post.

          Tap on to the image to get better visibility of content : 

          The approach is as follows.
          1. Wait for sometime to load the page for which data table is present.
          2. Take an integer variable say "dataTableActualRowCount" with 0 as the default value.
          3. Create  JavascriptExecutor object for the driver.
          4. Use jQuery "length" function technique within java-selenium code.
          5. jQuery stores the value in Object so convert it into integer and store the jquery returned length in
               dataTableActualRowCount
          6. Find the displayed count from bottom of the page using WebElement finder technique and store it
              in another integer variable say "displayedCountOfRowsOnPage".
          7. Now, Compare the values of "dataTableActualRowCount" and
                "displayedCountOfRowsOnPage".
          8. If dataTableActualRowCount == displayedCountOfRowsOnPage then "displayed row count
             on page is equals to data table row count " else "displayed row count on page is NOT equals
             to data  table row count".

          dataTableActualRowCount - calculating using jQuery "length" function
          int dataTableActualRowCount=0;

          JavascriptExecutor js
          =(JavascriptExecutor)driver;

          dataTableActualRowCount
          =((Number)js.executeScript("return $('#example').DataTable().rows().data().toArray().length;")).intValue();

          System
          .out.println("Data table row count="+dataTableActualRowCount);

          displayedCountOfRowsOnPage - finding through WebElement
          String displayedCount =driver.findElement(By.id("example_info")).getText().split("")[5];

          int displayedCountOfRowsOnPage = Integer.parseInt(displayedCount);

          System
          .out.println("Data table display count on page ="+displayedCountOfRowsOnPage);

          CompareDisplayedRowCountToDataTableRowCount.java
          package selenium.datatables;


          importorg.openqa.selenium.By;
          importorg.openqa.selenium.JavascriptExecutor;
          importorg.openqa.selenium.WebDriver;
          importorg.openqa.selenium.chrome.ChromeDriver;

          publicclassCompareDisplayedRowCountToDataTableRowCount{

          publicstatic WebDriver driver;
          publicstaticvoidmain(String[] args)throws Exception {

          System.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");
          System.setProperty("webdriver.chrome.silentOutput","true");

          driver =new ChromeDriver();
          driver.get("https://datatables.net/examples/basic_init/zero_configuration.html");
          driver.manage().window().maximize();
          compareDispalyedRowCountToActualRowCount();
          }


          publicstaticvoidcompareDispalyedRowCountToActualRowCount()throws Exception {
          Thread.sleep(10000);

          int dataTableActualRowCount=0;

          JavascriptExecutor js=(JavascriptExecutor)driver;

          dataTableActualRowCount =((Number)js.executeScript("return $('#example').DataTable().rows().data().toArray().length;")).intValue();
          System.out.println("Data table row count="+dataTableActualRowCount);

          String displayedCount = driver.findElement(By.id("example_info")).getText().split("")[5];

          int displayedCountOfRowsOnPage = Integer.parseInt(displayedCount);
          System.out.println("Data table display count on page ="+displayedCountOfRowsOnPage);

          if(Integer.compare(dataTableActualRowCount, displayedCountOfRowsOnPage)==0){
          System.out.println("Displayed count on page is equals to the data table row count ");
          }else{
          System.out.println("Displayed count on page is NOT equals to the data table row count");
          thrownewException("Displayed count on page is NOT equals to the data table row count");
          }
          }
          }


          I hope you find this tutorial is useful, stay tuned for more automation.!

          - Sadakar Pochampalli

          How to compare displayed drop down select values(actual values displayed) are matching with user expected drop down values for web data tables in java-selenium ? | How to automate page length options for data tables in selenium ?

          $
          0
          0
          Hi, in this post, we will learn about how to auto compare the displayed drop down select values to the user expected drop down values.

          i.e , compare "actual values displayed" to the "user expected values"  for the drop down select for a web data table.

          Zoom-In by tapping the image:

          The approach is as follows: 
          1) Declare a list for user expected values of an integer(later in the code convert to sting)
               or String type.
          2) Locate the drop down select element on the web using xpath locator technique.
          3) Create an object of "Select" class with the argument of  drop down select element. (from #2)
          4) Store the values of actual values displayed in another list of type WebElement
          5) Compare the two lists  and confirm the equality.

          user expected values
          List<Integer>expectedDropDownValues =new ArrayList<Integer>()
          {
          {
          add
          (10);
          add
          (25);
          add
          (50);
          add
          (100);
          }
          };

          actual values displayed
          WebElement entriesDropDownLocator = driver.findElement(By.xpath("//select[@name='example_length']"));

          Select entriesDropDown =new Select(entriesDropDownLocator);

          List
          <WebElement>actualDropDownValues =entriesDropDown.getOptions();

          Compare the two lists
          for(int i=0;i<actualDropDownValues.size();i++){

          if(actualDropDownValues.get(i).getText().equals(expectedDropDownValues.get(i).toString())){

          System
          .out.println("Value Matching :"+"Actual List Value="+actualDropDownValues.get(i).getText()+" And Expected Value="+expectedDropDownValues.get(i));
          }else{
          System
          .out.println("Value Not Matching :"+"Actual List Value="+actualDropDownValues.get(i).getText()+" And Expected Value="+expectedDropDownValues.get(i));
          }
          }

          CompareDisplayedDropdownSelectValuesWithActualValues.java
          package selenium.datatables;

          importjava.util.ArrayList;
          importjava.util.List;
          importorg.openqa.selenium.By;
          importorg.openqa.selenium.WebDriver;
          importorg.openqa.selenium.WebElement;
          importorg.openqa.selenium.chrome.ChromeDriver;
          importorg.openqa.selenium.support.ui.Select;


          publicclassCompareDisplayedDropdownSelectValuesWithActualValues{

          publicstatic WebDriver driver;

          publicvoidcompareDispalyedRowCountToActualRowCount()throws Exception {

          @SuppressWarnings("serial")
          List<Integer> expectedDropDownValues =new ArrayList<Integer>()
          {
          {
          add(10);
          add(25);
          add(50);
          add(100);
          }
                   };

          System.out.println("Expected dropdown values for accounts table");

          for(Integer expectedOptions : expectedDropDownValues){
          System.out.println(expectedOptions.toString());
          }

          WebElement entriesDropDownLocator = driver.findElement(By.xpath("//select[@name='example_length']"));

          Select entriesDropDown =new Select(entriesDropDownLocator);
          List<WebElement> actualDropDownValues = entriesDropDown.getOptions();

          System.out.println("Actual dropdown values from accounts table");
          for(WebElement actualValues : actualDropDownValues){
          System.out.println(actualValues.getText());
          }
          System.out.println("Compare the actual values with the expected values for dropdown");

          for(int i=0;i<actualDropDownValues.size();i++){

          if(actualDropDownValues.get(i).getText().equals(expectedDropDownValues.get(i).toString())){

          System.out.println("Value Matching :"+"Actual List Value="+actualDropDownValues.get(i).getText()+" And Expected Value="+expectedDropDownValues.get(i));
          }else{
          System.out.println("Value Not Matching :"+"Actual List Value="+actualDropDownValues.get(i).getText()+" And Expected Value="+expectedDropDownValues.get(i));
          }
          }
          }

          publicvoidcloseDriver(){
          driver.close();
          }
          publicvoidquitDriver(){
          driver.quit();
          }

          publicstaticvoidmain(String[] args)throws Exception {

          CompareDisplayedDropdownSelectValuesWithActualValues c =new CompareDisplayedDropdownSelectValuesWithActualValues();

          System.setProperty("webdriver.chrome.driver","D:\\006_trainings\\chromedriver.exe");
          System.setProperty("webdriver.chrome.silentOutput","true");

          driver =new ChromeDriver();
          driver.get("https://datatables.net/examples/basic_init/zero_configuration.html");
          driver.manage().window().maximize();
          c.compareDispalyedRowCountToActualRowCount();

          c.closeDriver();
          c.quitDriver();
          }
          }

          Console Log:
          Expected dropdown values for accounts table
          10
          25
          50
          100
          Actual dropdown values from accounts table
          10
          25
          50
          100
          Compare the actual values with the expected values for dropdown
          Value Matching :Actual List Value=10 And Expected Value=10
          Value Matching :Actual List Value=25 And Expected Value=25
          Value Matching :Actual List Value=50 And Expected Value=50
          Value Matching :Actual List Value=100 And Expected Value=100

          I hope you find this post is useful, stay tuned for more automation.!

          Tip : How to fix --> DEBUG cache:45 - Couldn't find template in cache for "index.ftl"("en", UTF-8, parsed); will try to load it. Or TemplateLoader.findTemplateSource("index_en.ftl"): Not found

          $
          0
          0
          Hi,

          When you receive the following DEBUG for Maven based cucumber java selenium project that is configured with extent reports, it can be fixed in log4j.properties by adding the following property.

          Fix : in log4j.properties
          log4j.logger.freemarker.cache= INFO, CONSOLE

          Issue:
          2020-06-0509:13:30 DEBUG cache:45- Couldn't find template in cache for"index.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:30 DEBUG cache:45- TemplateLoader.findTemplateSource("index_en.ftl"): Not found
          2020-06-0509:13:30 DEBUG cache:45- TemplateLoader.findTemplateSource("index.ftl"): Found
          2020-06-0509:13:30 DEBUG cache:45- Loading template for"index.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/index.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"head.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("head_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("head.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"head.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/head.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"nav.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("nav_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("nav.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"nav.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/nav.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"test-view/test-view.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("test-view/test-view_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("test-view/test-view.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"test-view/test-view.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/test-view/test-view.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"test-view/test-view-charts.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("test-view/test-view-charts_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("test-view/test-view-charts.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"test-view/test-view-charts.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/test-view/test-view-charts.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"test-view/bdd.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("test-view/bdd_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("test-view/bdd.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"test-view/bdd.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/test-view/bdd.ftl"
          2020-06-0509:13:31 DEBUG cache:45-"test-view/bdd.ftl"("en", UTF-8, parsed) cached copy not yet stale; using cached.
          2020-06-0509:13:31 DEBUG cache:45-"test-view/bdd.ftl"("en", UTF-8, parsed) cached copy not yet stale; using cached.
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"category-view/category-view.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("category-view/category-view_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("category-view/category-view.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"category-view/category-view.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/category-view/category-view.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"author-view/author-view.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("author-view/author-view_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("author-view/author-view.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"author-view/author-view.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/author-view/author-view.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"exception-view/exception-view.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("exception-view/exception-view_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("exception-view/exception-view.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"exception-view/exception-view.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/exception-view/exception-view.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"dashboard-view/dashboard-view.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("dashboard-view/dashboard-view_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("dashboard-view/dashboard-view.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"dashboard-view/dashboard-view.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/dashboard-view/dashboard-view.ftl"
          2020-06-0509:13:31 DEBUG cache:45- Couldn't find template in cache for"logs-view/testrunner-logs-view.ftl"("en", UTF-8, parsed); will try to load it.
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("logs-view/testrunner-logs-view_en.ftl"): Not found
          2020-06-0509:13:31 DEBUG cache:45- TemplateLoader.findTemplateSource("logs-view/testrunner-logs-view.ftl"): Found
          2020-06-0509:13:31 DEBUG cache:45- Loading template for"logs-view/testrunner-logs-view.ftl"("en", UTF-8, parsed) from "jar:file:/C:/Users/sadakarp/.m2/repository/E1SmapiUiAutomation/E1SmapiUiAutomation/0.0.1-SNAPSHOT/E1SmapiUiAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/com/aventstack/extentreports/view/html-report/logs-view/testrunner-logs-view.ftl"
          Viewing all 261 articles
          Browse latest View live


          <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>