Automation QA Testing Course Content

TestNG Framework & Programs

TestNG is a next-generation testing framework. designed to simplify a broad range of testing needs, from unit testing (testing a class in isolation of the others) to integration testing (testing entire systems made of several classes, several packages, and even several external frameworks, such as application servers).



Advantages:

  1. TestNg provides rich annotation support
  2. TestNg generates better html/xslt reports
  3. we can prioritize the testcases(@Test methods)ex: @Test(priority=1)
  4. we can skip the testcases ex:@Test(enabled=false)
  5. we can set dependancy among the test methods ex:@Test(dependsOnMethods={"test1"})
  6. we can group the test cases ex:@Test(groups={"smoke/sanity/regression"})
  7. we can run the testcases parallally on multiple browsers
  8. we can do datadriven testing using @DataProvider annotation
  9. we can supply parameter values from xml file using @Parameters annotation

Installing TestNG in Eclipse:

Install via Eclipse Marketplace

Go to the TestNG page on the Eclipse Market Place and drag the icon called "Install" onto your workspace.

Install from update site:

  • Go to Help --> Install New Software...
  • Enter the update site URL in "Work with:" field:
  • Make sure the check box next to URL is checked and click Next.
  • Eclipse will then guide you through the process.

Writing a test is typically a three-step process:

  • Write the business logic of your test and insert TestNG annotations in your code.
  • Add the information about your test (e.g. the class name, the groups you wish to run, etc...) in a testng.xml file or in build.xml.
  • Run TestNG.

2. Annotations:

  • @BeforeSuite: The annotated method will be run before all tests in this suite have run.


@BeforeSuite

public void beforeSuite(){

//write the code

}
  • @AfterSuite: The annotated method will be run after all tests in this suite have run.


@AfterSuite

public void afterSuite(){

//code here

}
  • @BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.


@BeforeTest

public void beforeTest(){



//code here;
}
  • @AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.


@AfterTest

public void afterTest(){

//code here;

}
  • @BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@BeforeGroups
public void beforeGroups(){
//code here;
}

  • @AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
@AfterGroups
public void afterGroups(){
//code here;
}
  • @BeforeClass: The annotated method will be run before the first test method in the current class is invoked.


@BeforeClass

public void beforeClass(){

//precondition code for test

}
  • @AfterClass: The annotated method will be run after all the test methods in the current class have been run.

@AfterClass

public void afterClass(){

destroycode;

}
  • @BeforeMethod: The annotated method will be run before each test method.

@BeforeMethod

public void setup(){

precondition code for every testcode

}
  • @AfterMethod: The annotated method will be run after each test method.
@AfterMethod

public void tearDown(){

destroycode;

}
  • @DataProvider: Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
Example:
  public class DataproviderDemo{
  
  @DataProvider(name="name of the dataprovider")
  public Object[][] methodName(){
  
  Object[][] data=new Object[rows][cols];
  //rows tells you number of times test has to be executed
  //columns will tell you number of parameters in the test 
  mehod
  Object[][] data=new object[3][2];
  //first row
  data[0][0]="uname1";
  data[0][1]="pwd1";
  //2nd row
  data[1][0]="uname2";
  data[1][1]="pwd2";
  
  //3rd row
  data[2][0]="uname3";
  data[2][1]="pwd3";
  return data;
  }
  @Test(dataProvider="dataprovidername/dataprovidermethodname")
  public void loginTest(String uname,String pwd){
  
  Sop(uname+"  "+pwd);
  }
  }
    
  }
------------------------------------------------------------
@Parameters: Describes how to pass parameters to a @Test method.
To do this, we need to declare parameter tag in xml file


 using 'name' and 'value' attribute.

Where the name attribute of the tag defines name of the

 parameter and the value attribute defines the value of the 

 parameter.
parameter names are declared inside the class and above the
method
syntax:
public class ParameterDemo{
@Parameters({"parameter1","parameter2",..})
@Test
public void test(String parameter1,String parameter2){

//type the username
driver.findElement(By.name("")).sendKeys(parameter1);
//type the password
driver.findElement(By.name("")).sendKeys(parameter2);
logic inside the method
}

}
How To Create an testng.xml file for particular class
1)right click on the class
2)select TESTNG option-->convert to testNG
3)give the suite name,test name and xml file location
4)click on finish button

//parameter values will be supplied from testng.xml file
testng.xml format
----------------------------------------------------------------------------
<suite name="suitename" parallel="none">
<test name="testname">
<parameter name="parameter1" value="valueofparameter1"/>
<parameter name="parameter2" value="value of parameter2"/>
<classes>
 <class name="packagename.classname1"/>
 <class name="packagename.classname2"/>
 </classes>
 </test>
  </suite>
 ============================================
  • @Test: Marks a class or a method as part of the test.


@Test
public void methodTest(){
//only test steps;
}

@Test Keywords/Parameters:

dataProviderThe name of the data provider for this test method.
this keyword is used to map between @DataProvider and @Test
Syntax:
@Test(dataProvider="dataprovidername/dataprovidermethodname")



dependsOnGroups: The list of groups this method depends on.

Syntax:

@Test(dependsOnGroups={"groupname"})

public void dgroup(){}


dependsOnMethods: The list of methods this method depends on.

Syntax:

@Test(dependsOnMethods={"methodname1","method2"})

public void dmethod(){}


alwaysRun: If set to true, this test method will always be run even 

if it depends on a method that failed.
@Test(alwaysRun=true,dependsOnMethods={"t"})

public void t1(){}


description: The description for this method.

Syntax:
@Test(description="write small description")

enabled: Whether methods on this class/method are enabled.

Syntax:
@Test(enabled=false)--this test method will skip


expectedExceptions: The list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, this test will be marked a failure.
Syntax:

@Test(expectedExceptions={"e1","e2"..})

groups: The list of groups this class/method belongs to.

Grouping in Automation is a quite an interesting feature through which you can easily categorize your test cases based on requirements.


For Example- If we have 200 test cases out of these some are end-to-end test cases, some are functional test cases and some are regression or smoke test cases so if you don’t categorize these test cases these all test cases will come under one common category.

Group Selenium Script using TestNG

For grouping in Selenium, we have to use the TestNG feature through which we can create groups and maintain them easily.

    Syntax

@Test(groups={"groupname"})

public void methodname(){}

Example:

 @Test(groups={"Smoke"},priority=1,description="")
public void m1(){}


We can create multiple groups as well

Syntax
 @Test(groups={"group1","group2"})
public void methodname(){}

We can include and exclude groups through testng.xml file

After grouping in Selenium we can specify the include and exclude in testng.xml.

<include> – It tells testng.xml that which group we need to execute.


<exclude>- It tells testng.xml which group we have to Skip

------------------------------------------------------
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="SuiteGroups" parallel="none">
  <test name="Testgroups">
    <groups>
       <run>
          <include name="Smoke" />
          <exclude name="Regression"/>
       </run>
     </groups>
    <classes>
      <class name="testngDemo.TestGroupDemo"/>
<class name="testngDemo.TestGroupDemo122"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

I created a new tag called group, an inside group we have mentioned includes and excludes tags, and 

we have mentioned the group name, which we have to include and exclude.


Once you run the above xml it will run all the test cases, which belong to the Smoke group category.

invocationCount: The number of times this method should be invoked.

Syntax:

@Test(invocationCount=3)

successpercentage: The percentage of success expected from this method

Timeout: The maximum number of milliseconds this test should take.

@Test(timeOut=3000)

threadPoolSize: The size of the thread pool for this method. The method will be invoked from multiple threads as specified by invocationCount.

priority: The priority for this test method. Lower priorities will be scheduled first.
@Test(priority=1)
public void t1(){}
@Test(priority=2)
public void l1(){}

How to Specify the particular class methods using include & exclude tags?


You can also specify groups and methods to be included and excluded:
<suite name="nameofthesuite">
<test name="Regression1">
  <groups>
    <run>
      <exclude name="brokenTests"  />
      <include name="checkinTests"  />
    </run>
  </groups>
  
  <classes>
    <class name="test.IndividualMethodsTest">
      <methods>
        <include name="testMethod" />
<exclude name="test2"/>
      </methods>
    </class>
<class name="test.IndependentTest"/>
  </classes>
</test>
</suite>

TestNg Reports:

Importance of Reporting in Selenium?
Ans-1- Reports helps you to identify the status of the test case (Pass/Fail/Skip).

2- Using reports we calculate the time taken by each test case that helps to calculate ROI(Return of Investment).

3- You can share automation reports with your team and clients as well to share the status of testing progress etc.

TestNG will provide three types of reports?
1)First open Default test.html
2)Second open emailable-report.html
3)Third open Index.html

if you expand test-output folder under the same project you can find the above three reports.
--------------------------------------------------------------------------------------
ReportNg Reports:
we need two dependencies
1) ReportNG --[org.uncommons » reportng]
2)Google Guice Core Library
include below listeners tag in testNg.xml  after suite tag
<listeners>
      <listener class-name="org.uncommons.reportng.HTMLReporter"/>
      <listener class-name="org.uncommons.reportng.JUnitXMLReporter"/>
  </listeners>
==================================================================
How to generate a report in link format:
Reporter.log("<a href=\"D:\\screenshot\\error.jpg\">screenshot</a>");

wherever you are adding the above line of anchor tag just add the below line of code inside the method in first
System.getProperty("org.uncommons.reportng.escape-output","false");

if you want to open the screenshot in another/separate tab then change the 1544 line like below
Reporter.log("<a target=\"blank\" href=\"D:\\screenshot\\error.jpg\">screenshot</a>");
if you want to add a small thumbnail in the reports.
Reporter.log("<a target=\"blank\" href=\"D:\\screenshot\\error.jpg\">screenshot</a>");
Reporter.log("<br>");
Reporter.log("<a target=\"blank\" href=\"D:\\screenshot\\error.jpg\"><img src=\"D:\\screenshot\\error.jpg\" height=200 width=200></img></a>");
======================================================================

How to Run Parallel tests, classes, and methods

=======================================================================
The parallel attribute on the <suite> tag can take one of the following values:
<suite name="My suite" parallel="methods" thread-count="5">
view source print?
<suite name="My suite" parallel="tests" thread-count="5">
<suite name="My suite" parallel="classes" thread-count="5">
<suite name="My suite" parallel="instances" thread-count="5">

parallel="methods": TestNG will run all your test methods in separate threads. Dependent methods will also run in separate threads but they will respect the order that you specified.

parallel="tests": TestNG will run all the methods in the same <test> tag in the same thread, but each <test> tag will be in a separate thread. This allows you to group all your classes that are not thread-safe in the same <test> and guarantee they will all run in the same thread while taking advantage of TestNG using as many threads as possible to run your tests.

parallel="classes": TestNG will run all the methods in the same class in the same thread, but each class will be run in a separate thread.

parallel="instances": TestNG will run all the methods in the same instance in the same thread, but two methods on two different instances will be running in different threads.

How to Set preserve-order:

If you want your classes/methods to be run in an 

unpredictable order, then we should go for 
the preserve-order attribute in testng. In TestNg by default 
the preserve-order attribute will be set
 to 'true', this means, TestNG will run your tests in the
 the order they are found in the XML file.

 xml file:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Preserve order test runs">
  <test name="Regression on preserve-order" preserve-order="false">
    <classes>
      <class name=" preserve.FetchSearchResults"/>
      <class name=" preserve.LocaleTesting"/>
      <class name=" preserve.GmailOnlinePeople"/>
    </classes>
  </test>
</suite> 
=================================================

TestNG Assertions:

  assertEquals("expresult", "actualvalue");-it compares the exp and actual value
the actual value can be get from webdriver methods
assertTrue(boolean commands):
assertTrue(boolean commands,"customized message");
assertTrue(web element. boolean command): you are expecting the element state should be true
---------------------------------------------------------------------------------------
Soft Assertions using TestNG
Posted on September 11, 2013
All of us write various automation tests for the application that we test in our every day work. One thing that has been debated the most is the use of soft assertions. Before we dive deep into the debate, a quick look at the two types of assertions.

Hard Assertions (or simply Assertions)

Tests immediately fail and stop executing the moment a failure occurs in the assertion. You may want to use a hard assert if you want to verify if you have logged in correctly and fail the test if you haven’t as there is no point in proceeding further if the test if the pre-condition itself fails.

Soft Assertions

Tests don’t stop running even if an assertion condition fails, but the test itself is marked as a failed test to indicate the right result. This is useful if you are doing multiple validations in a form (well.. you may actually question why you should be doing multiple validations in the first place which is probably a separate topic by itself), you may actually want to complete all the validations and fail the test once all validations are complete in case of failures.

Now.. there are multiple ways of doing soft asserts. You can write your own custom logic using the regular assert, but trap any exceptions and make the test proceed further. Or, you can use the TestNG library (for Java) which does this magic for you.

Here is how you initialize the TestNG assertions…

package automation.tests;

import org.testng.asserts.Assertion;
import org.testng.asserts.SoftAssert;

public class MyTest {
  private Assertion hardAssert = new Assertion();
  private SoftAssert softAssert = new SoftAssert();
}

Here is a sample test for a Hard Assertion…

@Test
public void testForHardAssert() {
  hardAssert.assertTrue(false);
}

Here is a sample test for Soft Assertion which does not fail the test…

@Test
public void testForSoftAssertWithNoFailure() {
  softAssert.assertTrue(false);  
}

And here is a soft assertion that actually marks the test as a failure…

@Test
public void testForSoftAssertionFailure() {
  softAssert.assertTrue(false);
  softAssert.assertEquals(1, 2);
  softAssert.assertAll();
}

If you look at the above test, the softAssert.assertAll() does the trick. This method collates all the failures and decides whether to fail the test or not at the end. So instead of writing a custom logic, the TestNG library itself offers the facility to perform Soft Assertions in your test.
 ================================================

Rerunning failed tests:

Every time tests fail in a suite, TestNG creates a file called testing-failed.xml in the output directory. This XML file contains the necessary information to rerun only these methods that failed, allowing you to quickly reproduce the failures without having to run the entirety of your tests.  Therefore, a typical session would look like this:
view sourceprint?
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -d test-outputs testng.xml
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -d test-outputs test-outputs\testng-failed.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite guice-stage="DEVELOPMENT" name=" Failed suite [Default suite]">
  <test name="Default test(failed)">
    <classes>
      <class name="testng.dataprovider.FbDataProvider">
        <methods>
          <include name="siginToFb" invocation-numbers="0 1"/>
          <include name="launchBrowser"/>
          <include name="closeBrowser"/>
        </methods>
      </class> <!-- testng.dataprovider.FbDataProvider -->
    </classes>
  </test> <!-- Default test(failed) -->
</suite> <!-- Failed suite [Default suite] -->
 ==============================================

How to Solve java.lang.NoClassDefFoundError: com/google/inject/Injector


java.lang.NoClassDefFoundError: com/google/inject/Injector
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at org.eclipse.golo.runtime.Module.metadata(Module.java:23)
    at org.eclipse.golo.runtime.Module.augmentations(Module.java:38
Caused by: java.lang.ClassNotFoundException: com.google.inject.Injector
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 62 more
Solution for the above issue is: include below dependency in pom.xml
In 7.0.0 pom below was the dependency information on guice
<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>4.1.0</version>
    <classifier>no_aop</classifier>
    <scope>provided</scope>
</dependency>
In 7.1.0 pom below was the dependency information on guice
<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>4.1.0</version>
    <classifier>no_aop</classifier>
    <scope>compile</scope>
</dependency>

=============================
TESTNG Interview Questions:
1)In TestNg class, if we don't give any priority for the test methods then what will be the order of your test case execution.

2)For example We have four methods under the TestNG class, two we set a priority, and the other two we didn't set a priority so what is the order of the test case execution.

3)Can we give priority as zero?

4)Can we give -ve values as a priority.

5)Can we give decimal values for priority.

6)We have given the same priority for all the methods, then what will be the order of the Test case execution.

7)In TestNG Class, a few methods we set priority, and few methods are not set the priority, then what is the order of the execution?

8)If we give the same priority for both methods then which one will get executed first.

9)We have multiple test methods (for example 4 methods) and we have given priority as 1,2,3 & 4. And the fourth method we set depends on the method on the third one, now what is the sequence of the execution now?

10)In the Junit and TestNG framework which one will you prefer and why?

11)a)What are Listerner's

b)Can you list out the Listeners.

c)Why do you need Listeners.

d)What is the main purpose of the listener.

e)What are the methods.

12)In TestNg Class we have many methods and in those methods, any two methods he wants to run sequentially and multiple times then how can we run it.
===============================================================
TESTNG PROGRAMS:
----------------------------------------------------------------------------
Program1:
Google Search data-driven program with all annotations
--------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeClass;

import java.time.Duration;

import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;

public class GoogleSearchDataDrivenTest {
private WebDriver driver = null;
private WebDriverWait wait = null;

@Test(dataProvider = "dp")
public void searchTest(String s) {
Reporter.log("started executing the searchTest() for keyword:" + s);
Reporter.log("type the " + s + "  keyword in search editbox.");
driver.findElement(By.name("q")).sendKeys(s);
Reporter.log("submit on the search editbox");
driver.findElement(By.name("q")).submit();
Reporter.log("verify the search results page title");
wait.until(ExpectedConditions.titleContains(s + " - Google Search"));
Reporter.log("verify the search results count text is present in the webpage or not.");
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("result-stats")));

Reporter.log("fetch the search results count text");
String txt = driver.findElement(By.cssSelector("div#result-stats")).getText();
System.out.println("search results text is:" + txt);
Reporter.log("search results text for " + s + " is :" + txt);
// extract the only count from search results count text.
// String txt="About 5,35,00,000 results (0.45 seconds)";
// using String class -split(delimiter) returns String[]
String[] str = txt.split(" ");
// String[] str=["About","5,35,00,000","results","(0.45","seconds)"]
// 0 1 2 3 4
System.out.println("search results count is:" + str[1]);
Reporter.log("search results count for " + s + " is:" + str[1]);
String s1 = str[1].replace(",", ""); // 53500000
// how can you convert String into long number
long count = Long.parseLong(s1);
System.out.println("search results count in primitive format:" + count);
Reporter.log("search results count for " + s + " in primitive format:" + count);
Reporter.log("****end of searchTest() for:" + s + " completed******");
}

@BeforeMethod
public void beforeMethod() {
Reporter.log("launch the application url");
driver.get("http://google.com/");
Reporter.log("wait for the page title -Google");
wait.until(ExpectedConditions.titleContains("Google"));
Assertions.assertEquals("Google", driver.getTitle());
Assertions.assertTrue(driver.getTitle().contains("Google"));

}

@AfterMethod
public void afterMethod() {
Reporter.log("started executing the @AftreMethod.. ");
Reporter.log("clear the cache");
driver.manage().deleteAllCookies();
}

@DataProvider
public Object[][] dp() {
Object[][] data = new Object[3][1];
// 1st row
data[0][0] = "selenium";
// 2nd row
data[1][0] = "UFT";
// 3rd row
data[2][0] = "cucumber";
return data;
}

@BeforeClass
public void beforeClass() {
Reporter.log("@Beforeclass is current class level annotation");
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome99\\chromedriver_win32\\chromedriver.exe");

Reporter.log("interface variablename=new classname();");
driver = new ChromeDriver();

Reporter.log("maximize the window");
driver.manage().window().maximize();

Reporter.log("add implicit wait");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Reporter.log("create WebDriverWaitobject");
wait = new WebDriverWait(driver, Duration.ofMillis(30000));

}

@AfterClass
public void afterClass() {
Reporter.log("quit the browser");
if (driver != null) {
driver.quit();
}
}

@BeforeTest
public void beforeTest() {
Reporter.log("This annotated method will repeat for every test tag<test name=\"testyag\" >");
Reporter.log(
"before any @Test in the test tag inside executiong first @BeforeTest mehtod block will be executed");
}

@AfterTest
public void afterTest() {

Reporter.log("after all @Test in the test tag have completed then @AfterSuite mehtod block will be executed");

}

@BeforeSuite
public void beforeSuite() {
Reporter.log("started executing the @BeforeSuite annotation mehtod block");
Reporter.log("before any @Test in the suite first @BeforeSuite annotation mehtod block will be executed");
}

@AfterSuite
public void afterSuite() {
Reporter.log("started executing the @AftereSuite annotation mehtod block");
Reporter.log(
"Aftre aall @Test in the suite have compelted finally @AfterSuite annotation mehtod block will be executed");
}

}

--------------------------------------------------------------------------------
Program2:
Create 4 @Test methods and demo the @Test keywords
like priority, description,enabled,timeOut,invocationCount
-----------------------------------------------------------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;

public class ZKDemoest {
private WebDriver driver = null;
private WebDriverWait wait = null;

@Test(description = "fetch all the buttons and print",priority=4,invocationCount=3)
public void buttonTest() {
Reporter.log("Started executing the buttonTest()...");
Reporter.log("click on Button link");
driver.findElement(By.linkText("Button")).click();
String pgTitle = "ZK Live Demo - Button";
wait.until(ExpectedConditions.titleContains(pgTitle));
Assertions.assertEquals(pgTitle, driver.getTitle());
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("breadCrumb")));
Reporter.log("Fetch all the buttons");
List<WebElement> buttonList = driver.findElements(By.className("z-button"));
Reporter.log("No of buttons in the page:" + buttonList.size());
for (WebElement btn : buttonList) {
Reporter.log("button name is:" + btn.getText());
}

Reporter.log("****end of buttonTest******");
}

@Test(description = "check all the checkboxes",priority=3,enabled=false)
public void checkboxTest() throws InterruptedException {
Reporter.log("Started executing the checkboxTest()...");
Reporter.log("click on Checkbox link");
driver.findElement(By.linkText("Checkbox")).click();
String pgTitle = "ZK Live Demo - Checkbox";
wait.until(ExpectedConditions.titleContains(pgTitle));
Assertions.assertEquals(pgTitle, driver.getTitle());
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("breadCrumb")));
Reporter.log("Fetch all the checkboxes");
List<WebElement> checkboxList = driver.findElements(By.xpath("//input[@type='checkbox']"));
Reporter.log("No of checkboxes in the page:" + checkboxList.size());
for (int i = 0; i < checkboxList.size(); i++) {
if (!checkboxList.get(i).isSelected()) {
checkboxList.get(i).click();
Thread.sleep(1000);
}
}
Reporter.log("fetch the checked checkboxes text");
String checkboxtxt = driver
.findElement(By.xpath("//span[contains(text(),'You have selected')]/following::span")).getText();
Reporter.log("checked checkboxes text is:" + checkboxtxt);
Reporter.log("****end of checkboxTest******");
}

@Test(description = "select the radiobutton",priority=2,timeOut=2000)
public void radioButtonTest() throws InterruptedException {
Reporter.log("Started executing the radioButtonTest()...");
Reporter.log("click on Radio Button link");
driver.findElement(By.linkText("Radio Button")).click();
String pgTitle = "ZK Live Demo - Radio Button";
wait.until(ExpectedConditions.titleContains(pgTitle));
Assertions.assertEquals(pgTitle, driver.getTitle());
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("breadCrumb")));
Reporter.log("select performance radio button ");
driver.findElement(By.xpath("//label[contains(text(),'Performance')]/preceding::input")).click();

Reporter.log("fetch the feature text");
String featureTxt = driver.findElement(By.xpath("//span[contains(text(),'Feature')]/following::span"))
.getText();
Reporter.log("Fetaure value is:" + featureTxt);
Reporter.log("select Forum radio button ");
driver.findElement(By.xpath("//label[contains(text(),'Forum')]/preceding::input")).click();

Reporter.log("fetch the WebSite text");
String websiteTxt = driver.findElement(By.xpath("//span[contains(text(),'Web Site')]/following::span"))
.getText();
Reporter.log("website value is:" + websiteTxt);

Reporter.log("select Developer Guide radio button ");
driver.findElement(By.xpath("//label[contains(text(),'Developer Guide')]/preceding::input")).click();

Reporter.log("fetch the Documentation text");
String docText = driver.findElement(By.xpath("//span[contains(text(),'Documentation')]/following::span"))
.getText();

Reporter.log("documentation text is:" + docText);
Reporter.log("****end of radioButtonTest******");
}

@Test(description = "handle the tweet popup/tab",priority=1)
public void tweetPopupTest() throws InterruptedException {
Reporter.log("Started executing the tweetPopupTest()...");
Reporter.log("click on Date and Time Picker link");
driver.findElement(By.linkText("Date and Time Picker")).click();
String pgTitle = "ZK Live Demo - Date and Time Picker";
wait.until(ExpectedConditions.titleContains(pgTitle));
Assertions.assertEquals(pgTitle, driver.getTitle());
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("breadCrumb")));

Reporter.log("switch to the iframe");
// identify the iframe webelement
WebElement ifrmele = driver.findElement(By.id("twitter-widget-0"));
driver.switchTo().frame(ifrmele);

Reporter.log("click on tweet button");
//driver.findElement(By.xpath("//*[contains(text(),'Tweet')]")).click();
WebElement tweetBtn=driver.findElement(By.xpath("//*[text()='Tweet']"));
JavascriptExecutor jsx=(JavascriptExecutor) driver;
jsx.executeScript("arguments[0].click()", tweetBtn);
Reporter.log("fetch all the window ids");
Set<String> handles = driver.getWindowHandles();
// convert the set collection into List collection
List<String> windowids = new ArrayList<>(handles);

// switch to Tweet window
driver.switchTo().window(windowids.get(1));
// wait for the tweet page title
wait.until(ExpectedConditions.titleIs("Twitter"));
// wait for the Want to log in first?
wait.until(ExpectedConditions
.presenceOfElementLocated(By.xpath("//div[@class='css-1dbjc4n r-18u37iz']/div/span")));
// perform the type action
driver.findElement(By.name("session[username_or_email]")).sendKeys("rameshn3@gmail.com");
Thread.sleep(3000);
//close the Twitter window
driver.close();
// switch back to parent window
driver.switchTo().window(windowids.get(0));
WebElement dateEditbox = driver.findElement(By.className("z-datebox-input"));
// clear the content in dateEditbox
dateEditbox.clear();
// type the date
dateEditbox.sendKeys("04/23/2022");

Reporter.log("****end of radioButtonTest******");
}

@BeforeMethod
public void beforeMethod() {
Reporter.log("launch the application url");
driver.get("https://www.zkoss.org/zkdemo/input");
Reporter.log("wait for the page title -ZK Live Demo - Input");
String pgTitle = "ZK Live Demo - Input";
wait.until(ExpectedConditions.titleContains(pgTitle));
Assertions.assertEquals(pgTitle, driver.getTitle());
Assertions.assertTrue(driver.getTitle().contains(pgTitle));
}

@AfterMethod
public void afterMethod() {
Reporter.log("started executing the @AftreMethod.. ");
Reporter.log("clear the cache");
driver.manage().deleteAllCookies();
}

@BeforeClass
public void beforeClass() {
Reporter.log("@Beforeclass is current class level annotation");
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome99\\chromedriver_win32\\chromedriver.exe");

Reporter.log("interface variablename=new classname();");
driver = new ChromeDriver();

Reporter.log("maximize the window");
driver.manage().window().maximize();

Reporter.log("add implicit wait");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Reporter.log("create WebDriverWaitobject");
wait = new WebDriverWait(driver, Duration.ofMillis(30000));

}

@AfterClass
public void afterClass() {
Reporter.log("quit the browser");
if (driver != null) {
driver.quit();
}
}

}
================================================
PROGRAM4:
Groups Testcase how to categorize the @Test methods
-----------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;

public class GroupsTest {
  @Test(groups="smoke")
  public void smoketest1() {
  System.out.println("GroupsTest class -smoketest1--functional");
  }
  
  @Test(groups="smoke")
  public void smoketest2() {
  System.out.println("GroupsTest class - smoketest2--functional");
  }
  
  @Test(groups="smoke")
  public void smoketest3() {
  System.out.println("GroupsTest classs - smoketest3--functional");
  }
  
  @Test(groups="regression")
  public void regresstest1() {
  System.out.println("GroupsTest classs - regressiontest1--functional");
  }
  
  @Test(groups="regression")
  public void regresstest2() {
  System.out.println("GroupsTest classs - regressiontest1--functional");
  }
  
  @Test(groups="regression")
  public void regresstest3() {
  System.out.println("GroupsTest classs - regressiontest3--functional");
  }
  
  
}
--------------------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;

public class GroupsTest2 {
  @Test(groups="smoke",priority=1)
  public void stest1() {
  System.out.println("GroupsTest2 classs - stest1--functional-GroupTest2");
  }
  
  @Test(groups="smoke",priority=3)
  public void stest2() {
  System.out.println("GroupsTest2 classs -stest2--functional-GroupTest2");
  }
  
  @Test(groups="smoke",priority=3)
  public void stest3() {
  System.out.println("GroupsTest2 classs - stest3--functional-GroupTest2");
  }
  
  @Test(groups="regression")
  public void regtest1() {
  System.out.println("GroupsTest2 classs - regtest1--functional-GroupTest2");
  }
  
  @Test(groups="regression")
  public void regtest2() {
  System.out.println("GroupsTest2 classs - regtest2--functional-GroupTest2");
  }
  
  @Test(groups="regression")
  public void regtest3() {
  System.out.println("GroupsTest2 classs - regtest3--functional-GroupTest2");
  }
  
  
}
------------------------------------------------------------------------
GroupsTestNG.xml file
----------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="GroupsSuite">
  <test thread-count="5" name="GroupsTest">
  <groups>
  <run>
  <include name="regression"></include>
  <exclude name="smoke"></exclude>
  </run>
  </groups>
    <classes>
      <class name="testngprograms.GroupsTest"/>
      <class name="testngprograms.GroupsTest2"/>
    </classes>
  </test> <!-- GroupsTest -->
</suite> <!-- GroupsSuite -->
--------------------------------------------------------------------------
Program 4:
-------------------------------------------------------------------------------
Typed keyword is present in Google Suggestions or not 

package testngprograms;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;

public class GoogleSuggestionAvailabilityCheckTest {
private WebDriver driver = null;
private WebDriverWait wait = null;
  @Test
  public void googleSuggestionAvailabilitycheckTest() {
  Reporter.log("open the url in browser");
driver.get("https://www.google.com/");
Reporter.log("wait and verify the Google page title");
String linkedinHomePgTitle = "Google";
wait.until(ExpectedConditions.titleIs(linkedinHomePgTitle));
Assert.assertEquals(driver.getTitle(), linkedinHomePgTitle);
Assert.assertTrue(driver.getTitle().contains(linkedinHomePgTitle));
Reporter.log("type selenium keyword in searc hedibtox");
String typekeyword="selenium";
driver.findElement(By.name("q")).sendKeys(typekeyword);;
//fetch all the suggestions into List collection
List<WebElement>suggestionList=driver.findElements(By.xpath("//ul[@role='listbox']/li"));
boolean isAvailable=false;
for(WebElement suggestion:suggestionList) {
String suggestiontext=suggestion.getText();
System.out.println(suggestiontext);
if(suggestiontext.contains(typekeyword)) {
isAvailable=true;
Assert.assertTrue(isAvailable,"typed keyword is not present in suggestionList");
}
}
  }
  
  
  
  
  @BeforeClass
public void beforeClass() {
// set the chromedriver.exe file path
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome99\\chromedriver_win32\\chromedriver.exe");
// interface refvar=new implementedclass();
driver = new ChromeDriver();
Reporter.log("Browser is launched");
Reporter.log("maximize the window");
driver.manage().window().maximize();
Reporter.log(" adding implicit wait");
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log(" create Object for WebDriverWait class");
wait = new WebDriverWait(driver, Duration.ofMillis(30000));

}

@AfterClass
public void afterClass() {
Reporter.log("close the browser in @AftreClass");
if (driver != null) {
driver.close();
}
}

}
---------------------------------------------------------------------
Program 5:
This program explains about @Parameters and dependsOnMethods and alwaysRun keywords
--------------------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;

public class DependsOnMethodsAndparametersTest {
private WebDriver driver = null;
private WebDriverWait wait = null;
  @Test
  public void linkedinHomePageTest() {
  Reporter.log("open the url in browser");
driver.get("https://www.linkedin.com/home");
Reporter.log("wait and verify the LinkedIn: Log In or Sign Up page title");
String linkedinHomePgTitle = "LinkedIn: Log In or Sign Up";
wait.until(ExpectedConditions.titleIs(linkedinHomePgTitle));
Assert.assertEquals(driver.getTitle(), linkedinHomePgTitle);
Assert.assertTrue(driver.getTitle().contains(linkedinHomePgTitle));
Reporter.log("Click on Signin link in Linkedin Home page ");
driver.findElement(By.cssSelector("a.nav__button-secondary")).click();
String singInPgTitle="LinkedIn Login, Sign in | LinkedIn";
wait.until(ExpectedConditions.titleIs(singInPgTitle));
Assert.assertEquals(driver.getTitle(), singInPgTitle);
Assert.assertTrue(driver.getTitle().contains(singInPgTitle));
  }
  
  @Parameters({"uname","pwd"})
  @Test(dependsOnMethods= {"linkedinHomePageTest"},alwaysRun=true)
  public void doLoginTest(String uname,String pwd) {
  
Reporter.log("Started executing the doLoginTest()....");
Reporter.log("Verify the Sign in Header text");
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h1.header__content__heading ")));
Reporter.log("type the username in username edibtox");
driver.findElement(By.id("username")).sendKeys(uname);
Reporter.log("type the pasword in passowrd edibtox");
driver.findElement(By.name("session_password")).sendKeys(pwd);
Reporter.log("click on login button");
driver.findElement(By.xpath("//button[@type='submit']")).click();
Reporter.log("wait for the page tile- Feed | LinkedIn");
wait.until(ExpectedConditions.titleContains("Feed | LinkedIn"));
  }

  @Test(dependsOnMethods= {"doLoginTest"})
  public void doLogoutTest() {
  Reporter.log("Started executing the doLogoutTest()...");
  wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[class*='feed-identity-module']")));
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[class*='feed-identity-module']")));
  Reporter.log("wait for the profile image icon");
  wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("img[class*='global-nav__me-photo ember-view']")));
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("img[class*='global-nav__me-photo ember-view']")));
  Reporter.log("click on profile image icon");
  driver.findElement(By.cssSelector("img[class*='global-nav__me-photo ember-view']")).click();
  WebElement signOutLink=driver.findElement(By.xpath("//a[@class='global-nav__secondary-link mv1'][contains(.,'Sign Out')]"));
  wait.until(ExpectedConditions.visibilityOf(signOutLink));
  Reporter.log("click on logout link");
  signOutLink.click();
  }
  
 @Parameters({"browser"})
@BeforeClass
public void setUp(String browser) {
Reporter.log("started executing the @BeforeClass");
if(browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome99\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}else if(browser.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "D:\\webdriverjars\\executables\\gecko30\\geckodriver-v0.30.0-win64\\geckodriver.exe");
FirefoxOptions opt=new FirefoxOptions();
opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
//interface refvar=new implementedclass();
driver=new FirefoxDriver(opt);
}else if(browser.equalsIgnoreCase("edge")) {
System.setProperty("webdriver.edge.driver", "D:\\webdriverjars\\executables\\edge98\\edgedriver_win64\\msedgedriver.exe");
driver = new EdgeDriver();
}
Reporter.log("maxmize the window");
driver.manage().window().maximize();

Reporter.log("add implicitwait");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Reporter.log("create object for WebDriverWait class");
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
}

@AfterClass
public void afterClass() {
Reporter.log("close the browser in @AftreClass");
if (driver != null) {
driver.close();
}
}

}
---------------------------------------------------------------------------
TestNG.xml file:
---------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="ParametersSuite">
  <test thread-count="5" name="ParametersTest">
<parameter name="browser" value="chrome"></parameter>
  <parameter name="uname" value="rameshqaonline@gmail.com"></parameter>
  <parameter name="pwd" value="welcome123$"></parameter>
    <classes>
      <class name="testngprograms.DependsOnMethodsAndparametersTest"/>
    </classes>
  </test> <!-- ParametersTest -->
</suite> <!-- ParametersSuite -->

================================================
PROGRAM6:
Select one option from Google suggestions
================================================package testngprograms;

import org.testng.annotations.Test;
import org.testng.asserts.Assertion;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;

public class GoogleSuggestionTest {
private WebDriver driver = null;
private WebDriverWait wait = null;

@Test
public void googleSuggestionTest() throws InterruptedException {
// open the google.com
driver.get("https://google.com");
wait.until(ExpectedConditions.titleIs("Google"));
Thread.sleep(2000);
// type the selenium keyword in search editbox.
WebElement searcheditbox = driver.findElement(By.name("q"));
searcheditbox.sendKeys("selenium", Keys.BACK_SPACE, "m");

String expKeyWord = "selenium download";

String suggestion;
do {
searcheditbox.sendKeys(Keys.ARROW_DOWN);

suggestion = searcheditbox.getAttribute("value");
Thread.sleep(2000);
if (suggestion.equals(expKeyWord)) {
searcheditbox.sendKeys(Keys.ENTER);
break;
}
Thread.sleep(2000);
} while (!suggestion.isEmpty());

Thread.sleep(1000);
// verify the search results count text is present in the webpage or not
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("result-stats")));
// fetch the search results count text and extract the only count from search
// results count text.
String txt = driver.findElement(By.xpath("//div[@id='result-stats']")).getText();
System.out.println("search results text is-->" + txt);
// String txt="About 3,99,00,000 results (0.59 seconds) ";
String[] str = txt.split(" ");
// str[]=["About","3,99,00,000","results","(0.59","seconds)"]
System.out.println("selenium results count is-->" + str[1]);

}

@Parameters({ "browser" })
@BeforeClass
public void setUp(String browser) {
Reporter.log("started executing the @BeforeClass");
if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome99\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver",
"D:\\webdriverjars\\executables\\gecko30\\geckodriver-v0.30.0-win64\\geckodriver.exe");
FirefoxOptions opt = new FirefoxOptions();
opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");

// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);

} else if (browser.equalsIgnoreCase("edge")) {
System.setProperty("webdriver.edge.driver",
"D:\\webdriverjars\\executables\\edge100\\edgedriver_win64\\msedgedriver.exe");

driver = new EdgeDriver();
}
Reporter.log("maxmize the window");
driver.manage().window().maximize();

Reporter.log("add implicitwait");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Reporter.log("create object for WebDriverWait class");
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
}

@AfterClass
public void afterClass() {
// close the browser
driver.close();
}

}
=================================================
PROGRAM7:
Select one option from twoplugins site suggestions using keys ARROW_DOWN

======================
package testngprograms;

import org.testng.annotations.Test;
import org.testng.asserts.Assertion;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;

import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;

public class SelectSuggestionBykeysTest {
private WebDriver driver = null;
private WebDriverWait wait = null;

/**
* 1)open the https://twoplugs.com url 
* 2)click on Live posting 
* 3)Type Toronto in searcheditbox
* 4)select Toronto, OH, USA value from suggestions
* @throws InterruptedException
*/
@Test
public void autoSuggestionBykeysTest() throws InterruptedException {
// open the google.com
driver.get("https://twoplugs.com");
wait.until(ExpectedConditions.titleIs("twoPLUGS - A plug for your Service and another for your Need"));
Thread.sleep(2000);
// click on Live posting
driver.findElement(By.xpath("//a[normalize-space()='Live Posting']")).click();

// identify the suggestion box
WebElement searcheditbox = driver.findElement(By.id("autocomplete"));
// clear the content in searcheditbox
searcheditbox.clear();
// Type Toronto in searcheditbox
searcheditbox.sendKeys("Toronto");
Thread.sleep(2000);
String suggestion;
do {
searcheditbox.sendKeys(Keys.ARROW_DOWN);

suggestion = searcheditbox.getAttribute("value");
Thread.sleep(2000);
if (suggestion.equals("Toronto, OH, USA")) {
searcheditbox.sendKeys(Keys.ENTER);
break;
}
Thread.sleep(2000);
} while (!suggestion.isEmpty());

}

@Parameters({ "browser" })
@BeforeClass
public void setUp(String browser) {
Reporter.log("started executing the @BeforeClass");
if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver",
"D:\\webdriverjars\\executables\\chrome99\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver",
"D:\\webdriverjars\\executables\\gecko30\\geckodriver-v0.30.0-win64\\geckodriver.exe");
// create Object for ChromeOptions
FirefoxOptions opt = new FirefoxOptions();
opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");

// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);

} else if (browser.equalsIgnoreCase("edge")) {
System.setProperty("webdriver.edge.driver",
"D:\\webdriverjars\\executables\\edge100\\edgedriver_win64\\msedgedriver.exe");

driver = new EdgeDriver();
}
Reporter.log("maxmize the window");
driver.manage().window().maximize();

Reporter.log("add implicitwait");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Reporter.log("create object for WebDriverWait class");
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
}

@AfterClass
public void afterClass() {
// close the browser
driver.close();
}

}
================================================
Parallel classes running suite file format:
--------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="ParallelclassesSuite" parallel="classes">
  <test thread-count="5" name="ParallelClassesTest" parallel="classes">
  <parameter name="browser" value="chrome"></parameter>
  <parameter name="uname" value="rameshqaonline@gmail.com"></parameter>
  <parameter name="pwd" value="welcome123$"></parameter>
    <classes>
      <class name="testngprograms.GoogleSuggestionTest"/>
      <class name="testngprograms.SelectSuggestionBykeysTest"/>
      <class name="testngprograms.DependsOnMethodsAndparametersTest"/>
    </classes>
  </test> <!-- ParallelClassesTest -->
</suite> <!-- ParallelclassesSuite -->
---------------------------------------------------------------------------------
Parallel Tests[cross browser testing] on different browsers testNg.xml format:
-----------------------------------------------------------------------------------<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="ParallelTestSuite" parallel="tests">
  <test thread-count="5" name="chromebrowserTest" parallel="tests">
  <parameter name="browser" value="chrome"></parameter>
    <classes>
      <class name="testngprograms.GoogleSuggestionTest"/>
    </classes>
  </test> <!-- ParallelTestTest -->
  <test thread-count="5" name="firefoxTest" parallel="tests">
  <parameter name="browser" value="firefox"></parameter>
  <parameter name="uname" value="rameshqaonline@gmail.com"></parameter>
  <parameter name="pwd" value="welcome123$"></parameter>
    <classes>
      <class name="testngprograms.DependsOnMethodsAndparametersTest"/>
    </classes>
  </test> <!-- ParallelTestTest -->
  
  <test thread-count="5" name="EdgeTest" parallel="tests">
  <parameter name="browser" value="edge"></parameter>
    <classes>
     
      <class name="testngprograms.SelectSuggestionBykeysTest"/>
      
    </classes>
  </test> <!-- ParallelTestTest -->
</suite> <!-- ParallelTestSuite -->


==================================

FILE UPLOAD WITH ROBOT CLASS
----------------------------------------------------------------------------------
Scenario Steps:
1)open the URL:https://easyupload.io/
2)Verify the page title :Easyupload.io - Upload files for free and transfer big files easily.
3)wait and verify the heading :Upload and share files for free
4)click on "click here or drop files to upload" button
5)call the robotclass method to handle uplaod file
6)click on Upload button
7)Verify File uploaded message assertion-assertTrue/assertEquals()
msg text:Your file has been uploaded successfully
8)Close the browser

-----------------------------------------------------
package testngprograms;

import org.testng.annotations.Test;

import basicprograms.WebDriverUtils;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.Reporter;


public class FileUploadUsingRobot {
WebDriver driver = null;
WebDriverWait wait = null;
WebDriverUtils wutils = null;
String fpath = "C:\\Users\\rames\\Downloads\\How to access Workday.pdf";

@Test
public void fileUploadByRobotTest() throws InterruptedException {
Reporter.log("open the url:https://easyupload.io/", true);
driver.get("https://easyupload.io/");
Reporter.log("verify the page title Easyupload.io - Upload files for free and transfer big files easily.", true);
wait.until(ExpectedConditions.titleContains("Easyupload.io - Upload files for free and transfer big files easily."));
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body > main > div > div.upload > h1")));
String headerTxt = driver.findElement(By.cssSelector("body > main > div > div.upload > h1")).getText();
Assert.assertEquals("Upload and share files for free", headerTxt);
Reporter.log("click on cclick here or drop files to upload button", true);
driver.findElement(By.xpath("//*[@id='dropzone']/div[2]/button")).click();
Reporter.log("call the robotclass method to handle uplaod file", true);
wutils.uploadFileWithRobot(fpath);
Reporter.log("click on Upload button", true);
driver.findElement(By.id("upload")).click();
Reporter.log("File uploaded message assertions", true);
wait.until(ExpectedConditions.presenceOfElementLocated(By.className("upload-success")));
Assert.assertTrue(driver.findElement(By.xpath("//div[@class='upload-success']/h5")).isDisplayed(), "file is not uploaded");
Assert.assertEquals("Your file has been uploaded successfully.",driver.findElement(By.xpath("//div[@class='upload-success']/h5")).getText());
Thread.sleep(2000);
}
@Parameters({ "browser" })
@BeforeClass(alwaysRun = true)
public void beforeClass(String browser) {
if (browser.equalsIgnoreCase("chrome")) {
ChromeOptions opt = new ChromeOptions();
opt.setAcceptInsecureCerts(true);
driver = new ChromeDriver(opt);
Reporter.log("chromebrowser is launched", true);
} else if (browser.equalsIgnoreCase("firefox")) {

FirefoxOptions opt = new FirefoxOptions();
opt.setAcceptInsecureCerts(true);
// opt.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
// interface refvar=new implementedclass();
driver = new FirefoxDriver(opt);
Reporter.log("firefox browser is launched", true);
} else if (browser.equalsIgnoreCase("edge")) {
EdgeOptions opt = new EdgeOptions();
opt.setAcceptInsecureCerts(true);
driver = new EdgeDriver(opt);
Reporter.log("edge browser is launched", true);
}
Reporter.log("maximize the window", true);
driver.manage().window().maximize();
Reporter.log("add implicitwait", true);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000));
Reporter.log("add explicitwait object", true);
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
Reporter.log("creating Object for WebDriverUtils class", true);
wutils = new WebDriverUtils(driver);
}

@AfterClass
public void afterClass() {
System.out.println("I am in AfterClass block");
// close the browser
driver.close();
}

}




================================
Problem:
while running the testNG Testcase from eclipse, got error below:
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.testng.log4testng.Logger.lambda$getLogger$0(Logger.java:30)
at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1705)
at org.testng.log4testng.Logger.getLogger(Logger.java:30)
at org.testng.TestNG.<clinit>(TestNG.java:111)
at org.testng.remote.support.RemoteTestNGFactory7_9.createRemoteTestNG(RemoteTestNGFactory7_9.java:16)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:67)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 6 more
--------------------------------------------------------------------
Solution:
1) if the propject type is plain java project --include the slf4j-api-2.0.13.jar in project classpath.
download from  link below:
https://mvnrepository.com/artifact/org.slf4j/slf4j-api/2.0.13
2)if project type is maven include below dependency in pom.xml

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.13</version>
</dependency>









No comments:

Post a Comment

Note: Only a member of this blog may post a comment.