0% found this document useful (0 votes)
133 views

Test NG

TestNG is an automation testing framework that uses annotations to identify test methods and configure test runs. It allows grouping of test cases, running tests in parallel, and generating detailed reports. Key features include support for parameters, data providers to pass multiple data sets to test methods, and listeners to perform actions based on test results. TestNG configuration and tests are defined using an XML file, while annotations identify test methods, configure method execution order, and group tests.

Uploaded by

pravin kumbhar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views

Test NG

TestNG is an automation testing framework that uses annotations to identify test methods and configure test runs. It allows grouping of test cases, running tests in parallel, and generating detailed reports. Key features include support for parameters, data providers to pass multiple data sets to test methods, and listeners to perform actions based on test results. TestNG configuration and tests are defined using an XML file, while annotations identify test methods, configure method execution order, and group tests.

Uploaded by

pravin kumbhar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

TestNG
What is TestNG?
TestNG is an automation testing framework in which NG stands for “Next
Generation”.TestNG is inspired by Junit which uses the annotations(@).
Features of TestNG we can use in selenium
-WebDriver has no native mechanism for generating reports. TestNG can generate the
report in a proper and readable format.
-Multiple test cases can be grouped more easily.
-The same test case can be executed multiple times without loops.
-Using TestNG , you can execute multiple test cases on multiple browsers.
-The TestNG framework can be easily integrated with tools like TestNG Maven, Jenkins ,
etc.
-Annotations used in the testing are very easy to understand ex:@BeforeMethod ,
@AfterMethod, @BeforeTest, @AfterTest
Points to remember for writing TestNG testcase.
1.TestNG does not require you to have a main() method.
2.Methods need not be static.
3.We used the @Test annotation . @Test is used to tell that the method under it is a test
case.
4.We needed to import the package org.testng.annotations.*.
5.We used the Assert class.
The Assert class is used to conduct verification operation in TestNG.
Assertions in TestNG are a way to verify that the expected result matches the actual result.
To use it , we need to import the org.testng.Assert package.

What are the different ways in which TestNG can be invoked?


You can invoke TestNG in several different ways:
Using Eclipse
With ant OR Maven
From the command line
Maven dependency to add in POM.xml file
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>test</scope>
</dependency>

2.TestXML File
What is TestNG XML File?
In TestNG framework, we need to create Testng xml file to run and handle multiple test
classes. TestNG.xml file which contains all the test configuration and this XML file can be
used to run and organize our test.
In testing.xml file, we configure our test run, set test dependency, include or exclude any
test, method, class or package and set priority etc.
Testng.xml file is also is used for TestNG Parameters. TestNG Parameters are the arguments
that we pass to the test methods.

3.Enable/Disable test cases and Regular Expression


In TestNG, test cases can be enabled/disabled in two ways .
-You can disable the test case in a @Test annotation.
TestNG @Test enable parameter
-You can disable the test case in the XML file
<methods>
<exclude name =”MethodName”/> --Disable
<include name =”MethodName”/> --Enable
</methods>
Regular Expression:
<methods>
<include name =”Method.*”/>
</methods>
4.TestNG Annotations
What are TestNG Annotation
An annotation is a tag/piece of code that provides additional information about the method.
It is represented by ‘@’ prefix. It is used to control the execution of the test cases.
Following are some of the benefits of using annotations
-TestNG identifies the methods it is interested in, by looking up annotations. Hence, method
names are not restricted to any pattern or format.
-We can pass additional parameters to annotations.
-Annotations are strongly typed, so the compiler will flag any mistakes right away.
TestNG Annotations

@BeforeSuite: The annotated method will run before all tests in this suite have.
@AfterSuite: The annotated method will run after all tests in this suite have.
@BeforeTest: The annotated method will run before any test method belonging to the
classes inside the <test> tag is run.
@AfterTest: The annotated method will run after all the test methods belonging to the
classes inside the <test> tag have run.
@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.
@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.
@BeforeClass: The annotated method will run before the first test method in the current
class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current
class have been run.
@BeforeMethod: The annotated method will be run before each test method.
@AfterMethod: The annotated method will be run after each test method.
@Test: This we need to use for test cases
@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.

5.TestNG Test Annotation Attributes

1. Description : It is a string which is attached to the @Test annotation that describes


the information about the test.
2. Priority: When no 'priority' attribute is specified then the TestNG will run the test
cases in alphabetical order. Priority determines the sequence of the execution of the
test cases. The priority can hold the integer values between -5000 and 5000. When
the priority is set, the lowest priority test case will run first and the highest priority
test case will be executed last. Suppose we have three test cases and their priority
values are -5000, 0, 15, then the order of the execution will be 0,15,5000. If priority
is not specified, then the default priority will be 0.
3. Enabled : The 'enabled' attribute contains the boolean value. By default, its value is
true. If you want to skip some test method, then you need to explicitly specify 'false'
value.
4. Dependsonmethods : Methods are used to execute its dependent method in the
same way dependsOnMethods works.
Example: @Test (dependsOnMethods = { "start", "init" })Groups.
5. timeout : If one of the test cases is taking a long time due to which other test cases
are failing. To overcome such situation, you need to mark the test case as fail to
avoid the failure of other test cases. The timeOut is a time period provided to the
test case to completely execute its test case.
6.TestNG Parameters
TestNG Parameters are the arguments that we pass to the test method. There are two ways
through which we can pass the parameters to the test methods.
TestNG Parameters (With XML file)
TestNG DataProvider
Syntax :
@Parameter({“parameter name”})
@Parameters({“param1”,”parm2”,”parm3”})

Assignment :
Test Data
Keyword :
1.selenium
2.Java
Test Steps :
Launch the browser and open wee.google.con
Add the first keyword as input in the search box .
Verify the input value on UI to be same as from test data
Repeat the above two steps for the other 2 keywords.
TestNG will automatically try to convert the value specified in testing.xml to the type of your
parameter.
Here are the types supported.
String
Int/Integer
Boolean/Bollean
byte/Byte
char/Chracter
double/Double
float/Float
long/Long
short/Short

7.Data Providers
Similar to TestNG Parameters, DataProviders are a means to pass data to test methods in
TestNG. Using DataProvider in TestNG, we can easily inject multiple values into the same
test case. It comes inbuilt in TestNG and is popularly used in data-driven frameworks.
Syntax:
@DataProvider(name=”name of the data provider”)
Public Object[][]daaProviderfunc()
{
return new Object[][]{values}
}
The DataProvider annotation has a single attribute called name, which you can select as per
your convenience.
DataProviders are separate methods used in test functions, which means that this
annotation is not used on test functions like the testNG parameters .
The DataProvider method retures a 2D list of objects.
In case you do not define a name for the DataProvider, the DataProvider method name is
considered its default name. So, the name of the DataProvider calls the DataProvider
method.
Test Scenario:
1.Launch the browser to open www.google.com
2.Search the first keyword combination.
3.Repeat the steps 2 for the other 2 keywords combination.
Search Key Words :
Country Monument
India Qutub Minar
Agra Taj Mahal
Hyderabad Charminar

8.Parallel Testing:
Parallel testing or parallel execution, as the name suggests, is a process of running the test
case parallelly rather than one after the other.
We can execute –
All the methods with @Test annotation will execute in parallel.
All the test cases inside a java class will run parallel methods.
All the test cases inside <test> tag of the Testing xml file will run parallel.
Where can we apply Parallel Test execution in TestNG?
Methods: This will run the parallel tests on all @Test methods in TestNG.
Tests: All the test cases present inside the <test> tag will run with this value.
Classes: All the test cases present inside the classes that exist in the XML will run in parallel.
Instances: This value will run all the test cases parallelly inside the same instance.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name = "Parallel Testing Suite" parallel = "methods" thread-count=”2”>
<test name = "Parallel Tests"
<classes>
<class name = "ParallelTest" />
</classes>
</test>
</suite>

9.Listeners
It is interface in TestNG.
Types of Listeners in TestNG
1. lAnnotationTransformer
2. lAnnotationTransformer2
3. ICinfigurable
4. IConfigurationListener
5. IExecutionListner
6. IHookable
7. IInvokedMethodListner
8. IInvokedMethodListner2
9. lMethodlnterceptor
10. IReporter
11. ISuiteListner
12. ITestListner – It is very popular
ITestListners in TestNG
ITestListener:
Based on the execution/result of the test cases if you can perform some certation action like
pass,fail,skipped the you can use listeners .
This is the most frequently used TestNG listener. ITestListener is an interface implemented
in the class , and that class overrides the ITestListener defined methods. The ITestListener
listens to the desired events and executes the methods accordingly.

It contains the following methods:


OnTestStart():An onTestStart() is invoked only when any test method gets started.
onTestSuccess():An onTestSuccess() method is executed on the success of the test method.
onTestFailure():An onTestFailure() method is invoked when test method fails.
onTestSkipped():An onTestSkipped() run only when any test method has been skipped.
onStart():An onStart() method is executed on the start of any test method.
onFnish():An onFinish() is invoked when any test case finishes its execution.
onTestFailedButWithinSuccessPercentage(): This method is invoked each time when the test
method fails but within success percentage.

You can use ITestListners in two ways –


1. Class Level
@Listeners(com.jbs.testNg.ITestListne.class)
2. TestNG XML file –
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" thread-count="2">
<listeners>
<listener class-name="com.jbs.testNg.ITestListne"></listener>
</listeners>
<test name="HRM Test">
<classes>
<class name="com.jbs.testNg.ParralTesting"/>
</classes>
</test> <!-- Test -->

Note : If you can use Listeners in TestNG XML file then not need to mentation in class .

10.Batch Testing:
What is Batch Testing:
Running multiple test cases in a suite is called Batch Testing.
A test suite is a collection of the test cases. Test suites help in grouping test cases.
You can categorize test suites based on functionality, module, environment, or something
else.
In TestNG we can use XML file to perform Batch Testing.
We can use below test suite for Batch Testing.

Sanity Test – Suite


<?xml version="1.0" encoding="UTF-8"?>
<suite name="SanityTest">
<test name="Sanity Test Cases">
<classes>
<class name="com.jbs.testNg.HomeScreenTest" />
<class name="com.jbs.testNg.LoginTest" />
</classes>
</test>
</suite> <!-- Suite -->
Functional Test-Suite
<?xml version="1.0" encoding="UTF-8"?>
<suite name="FunctionalTest">
<test name="Functional Test Cases">
<classes>
<class name="com.jbs.testNg.ProductPageTest" />
<class name="com.jbs.testNg.PaytmentTest" />
</classes>
</test>
</suite> <!-- Suite -->
MasterSuite:
<?xml version="1.0" encoding="UTF-8"?>
<suite name="MasterSuite">
<suite-fiels>
<suite-file
path="C:\Users\Subhash\eclipse-workspace\SeleniumProject\
FunctionalTest.xml">
<suite-file
path="C:\Users\Subhash\eclipse-workspace\SeleniumProject\
SanityTest.xml" />
</suite-file>
</suite-fiels>
</suite>

11.Assertion
Assertion in TestNG are used for validating the test methods and to verify that expected
result and the actual result matched or not.
Types of Assertions:
1. Hard Assertion
2. Soft Assertion
Hard Assertion:
Hard Assertion is an Assertion that immediately throws the AsserException when the test
case is failed.
A Hard Assertion contains the following methods.

Soft Assert:
Soft assert does not throw an exception immediately when the assertion is failed, collects
then and carries out with the next validation. This accumulates the errors in each @Test
execution.
To use testing soft assertion, you have to use testing SoftAssert class.
Test Scenario:
1. Launch Chrome browser.
2. Open URL-https://testautomationpractice.blogspot.com/
3. Verify Title of the webpage.
4. Verify the presence of the Wikipedia icon on web page.
5. Verify the presence of Wikipedia search button web page.

12.InvocationCount
Run Test cases multiple time without using loop.
@Test annotation – invocationCount attribute
In TestNG, InvocationCount attribute is used to run single test case multiple time.
Syntax:
@Test(invocationCount=null)
Where num=number of times you want to run this test method.

13.Cross Browser Testing


What is Cross Browser Testing.
Cross Browser Testing (CBT) is a process to perform tests on multiple browsers.
This is done to know how a website performs on different browsers.
Cross browser testing gives the confidence that the website behaviour is consistent across
various browsers.

14.Retry Failed Test Cases:


Why we re-run the test case when it fails.
There are multiple reasons why the test fails.
-Due to the network issue.
-Due to application downtime.
-Due to loading issue and etc.
But if the script is failing due to xpath and some valid reason then you have to maintain for
re work on your scripts.
How we Re Run Failed Test Cases In Selenium In case of Failure?
1. Using testng-failed.xml
2. Using IRetryAnalyzer interface that is part of TestNG and we need to override retry
method.
15.DataProvides with Excel
TestNG Parametrs.
TestNG parameters enable us to pass the values only once per execution cycle.
TestNG DataProvider :
DataProvider in TestNG allows us to pass multiple parameters to a single test in a single
execution . Using DataProviders, we can easily pass multiple values to a test in just one
execution cycle.

16.TestNG Reports:
TestNG Reports are the default HTML reports which are generated once the test cases are
executed using TestNG.
The TestNG will generate the default report.
-index.html
-emailable-report.html
-Report class – Used to log information in reports.
Note: Selenium web driver is used for automation the web-application, but it won’t
generate any reports.
Reporter Class Syntax:
Reporter class of TestNG provides us with four different methods to log information isn’t
that interesting? Here are some methods:
-Reporter.log(String s);
- Reporter.log(String s,Boolean logToStandardOut);
- Reporter.log(String s, int level);
- Reporter.log(String s,int level,Boolean logToStandardOut);

1. Reporter.log(String s); : This method logs the string passed into your HTML Report.
Parameters : S – The message to be logged.
2. Reporter.log(String s,Boolean logToStandardOut); :This method logs the string
passed into your HTML Report.
Additionally, it also prints the same message on your console if logToStandardOut is
set to TRUE.
Parameters :
S – The message to be logged.
logToStandardOut – Print the message on standard output.
3. Eporter.log(String s , int level); : This method logs the string passed into your HTML
Report if the current verbosity equals or is greater than the one passed in the
parameter.
Parameters :
S – The message to be logged.
level –The verbosity of the message to be logged.

What is verbosity level in TestNG?


The verbose Level in TestNG is used to define the amount of logging performed on
the console. The verbosity level ranges from 0 to 10, where 10 is the most detailed
logging level whereas 0 means minimal logging.

You can set the verbosity level in your testng.xml

<suite thread-count=”2” name=”TestNGReporterTest” parallel=”classes”


verbose=”10”>

4. Eporter.log(String s,int level,Boolean logToStandardOut); :


Parameters :
S – The message to be logged.
logToStandardOut – Whether to print the message on standard output as well

You might also like