Varun Menon NG Beginner's Guide 2013
NG%20Beginner's%20Guide%20-%20First%20Ed
User Manual: Pdf
Open the PDF directly: View PDF .
Page Count: 276 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Cover
- Copyright
- Credits
- About the Author
- Acknowledgement
- About the Reviewers
- www.PacktPub.com
- Table of Contents
- Preface
- Chapter 1: Getting Started
- Testing and test automation
- TestNG
- Features of TestNG
- Downloading TestNG
- Installing TestNG onto Eclipse
- Time for action – installing TestNG onto Eclipse
- Writing your first TestNG test
- Time for action – creating a Java project
- Time for action – creating your first TestNG class
- Running your first test program
- Time for action – running tests through Eclipse
- Summary
- Chapter 2: Understanding testng.xml
- About testng.xml
- Creating a test suite
- Time for action – creating a test suite
- Running testng.xml
- Time for action – running testng.xml through the command prompt
- Time for action – executing testng.xml using Eclipse
- Time for action – configuring Eclipse to run a particular TestNG XML file
- Creating multiple tests
- Time for action – testng XML with multiple tests
- Adding classes, packages, and methods to test
- Time for action – creating a test with classes
- Time for action – creating a test with packages
- Time for action – creating a test with methods
- Time for action – creating a test suite with package, class, and test method
- Including and excluding
- Time for action – test suite to include a particular package
- Time for action – test suite to exclude a particular package
- Time for action – test suite to exclude a particular method
- Time for action – using regular expressions for test
- Summary
- Chapter 3: Annotations
- Annotations in TestNG
- Before and After annotations
- Time for action – running the Before and After annotations
- Time for action – Before and After annotation when extended
- Test annotation
- Time for action – using test annotation on class
- Disabling a test
- Time for action – disabling a test method
- Exception test
- Time for action – writing an exception test
- Time for action – writing a exception test verifying message
- Time test
- Time for action – time test at suite level
- Time for action – time test at test method level
- Parameterization of test
- Time for action – parameterization through testng.xml
- Time for action – providing optional values
- DataProvider
- Time for action – using Test annotation on Class
- Time for action – DataProvider in different class
- Summary
- Chapter 4: Groups
- Grouping tests
- Time for action – creating test that belong to a group
- Running a TestNG group
- Time for action – running a TestNG group through Eclipse
- Time for action – running a TestNG group using the testng XML
- Test that belong to multiple groups
- Time for action – creating a test having multiple groups
- Including and excluding groups
- Time for action – including/excluding groups using the testng XML
- Using regular expressions
- Time for action – using regular expressions in the testng XML
- Default group
- Time for action – assigning a default group to a set of tests
- Group of groups
- Time for action – running a TestNG group using the testng XML
- Summary
- Chapter 5: Dependencies
- Dependency test
- Time for action – creating a test that depends on another test
- Time for action – creating a test that depends on multiple tests
- Time for action – creating a test that depends on inherited tests
- Dependent groups
- Time for action – creating a test that depends on a group
- Time for action – depending on a method from a different class
- Using regular expressions
- Time for action – using regular expressions
- XML-based dependency configuration
- Time for action – using simple dependency in XML
- Time for action – defining multigroup dependency in XML
- Time for action – using regular expressions for dependency
- Summary
- Chapter 6: The Factory Annotation
- What is factory?
- Time for action – first factory test
- Passing parameters to test classes
- Time for action – passing parameters to test classes
- Using DataProvider along with the @Factory annotation
- Time for action – using DataProvider with Factory
- DataProvider or Factory
- Time for action – the DataProvider test
- Time for action – the Factory test
- Dependency with the @Factory annotation
- Time for action – dependency with the @Factory annotation
- Time for action – running a dependency test sequentially
- Summary
- Chapter 7: Parallelism
- Parallelism
- Time for action – writing first parallel test
- Running test methods in parallel
- Time for action – running test methods in parallel
- Running test classes in parallel
- Time for action – running test classes in parallel
- Running tests inside a suite in parallel
- Time for action – running tests inside a suite in parallel
- Configuring an independent test method to run in multiple threads
- Time for action – running independent test in threads
- Advantages and uses
- Summary
- Chapter 8: Using Build Tools
- Chapter 9: Logging and Reports
- Logging and reporting
- Writing your own logger
- Time for action – writing a custom logger
- Writing your own reporter
- Time for action – writing a custom reporter
- TestNG HTML and XML report
- Time for action – generating TestNG HTML and XML reports
- Generating a JUnit HTML report
- Time for action – generating a JUnit report
- Generating a ReportNG report
- Time for action – generating a ReportNG report
- Generating a Reporty-ng (former TestNG-xslt) report
- Time for action – generating a Reporty-ng report
- Summary
- Chapter 10: Creating a Test Suite through Code
- Running TestNG programmatically
- Time for action – running TestNG programmatically
- Parameterization of tests
- Time for action – passing parameter values
- Include and exclude
- Time for action – including test methods
- Time for action – including/excluding groups
- Dependency test
- Time for action – configuring a dependency test
- Summary
- Chapter 11: Migrating from JUnit
- Running your JUnit tests through TestNG
- Time for action – writing a JUnit test
- Time for action – running JUnit tests through TestNG
- Time for action – running JUnit and TestNG tests together
- Running JUnit tests along with TestNG through Ant
- Time for action – running JUnit and TestNG tests through Ant
- Migrating from JUnit to TestNG
- Time for action – converting a JUnit test to a TestNG test
- Summary
- Chapter 12: Unit and Functional Testing
- Pop Quiz Answers
- Index
TestNg Beginner's Guide
Write robust unit and funconal tests with the
power of TestNG
Varun Menon
BIRMINGHAM - MUMBAI
TestNg Beginner's Guide
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmied in any form or by any means, without the prior wrien permission of the
publisher, except in the case of brief quotaons embedded in crical arcles or reviews.
Every eort has been made in the preparaon of this book to ensure the accuracy of the
informaon presented. However, the informaon contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark informaon about all of the
companies and products menoned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this informaon.
First published: July 2013
Producon Reference: 1190713
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-600-9
www.packtpub.com
Cover Image by Suresh Mogre (suresh.mogre.99@gmail.com)
Credits
Author
Varun Menon
Reviewers
Yagna Narayana Dande
Mihai Vilcu
Acquision Editor
Usha Iyer
Lead Technical Editor
Anila Vincent
Technical Editors
Praga Singh
Mausam Kothari
Dipika Gaonkar
Sampreshita Maheshwari
Hardik B. Soni
Project Coordinator
Rahul Dixit
Proofreaders
Lindsey Thomas
Bernadee Watkins
Indexers
Hemangini Bari
Tejal R. Soni
Rekha Nair
Priya Subramani
Producon Coordinator
Nitesh Thakur
Cover Work
Nitesh Thakur
About the Author
Varun Menon is a QA consultant with several years of experience in developing
automaon frameworks on various technologies and languages such as Java, JavaScript,
Ruby, and Groovy. He has worked on web and mobile applicaons for some of the leading
clients in the eld of supply chain management, online photo books, video analycs, and
market research.
He blogs at http://blog.varunin.com and is acve on Stack Overow, Selenium,
and roboum groups. He is also the author of an upcoming open source android
automaon tool Bot-bot, which has record and re-play features like Selenium.
He currently holds the posion of QA Architect at Prama Technologies Private Limited,
Hyderabad, India.
Acknowledgement
First of all I would like to thank my mother and father for supporng me and guiding me on
the correct path throughout my life.
I would like to thank my wife, Sandhya, who has tolerated me and my passion towards work
and has always been supporve. Thanks for all your support.
I would like to thank Prama Technologies where I have learned most of the things that
I know now. I would like to thank Mr Jay and Vijay Pullur for starng such a wonderful
company and providing such a great environment to learn and work.
I would like to thank my managers, Reddy Raja and Sharad Solanki, without their support,
inspiraon, and movaon I may not have been able to reach my current posion. A special
thanks to Apurba Nath and Rohit Rai for relying on me and my skills.
I would like to thank all my friends without whom life may not be as fruiul as it is now.
I would also like to thank Cedric Beust, the creator of TestNG unit tesng framework, for
coming up with such a good unit test framework, for solving developer and QA engineer's
problems and for being an inspiraon of what we can aspire to in QA.
Last but by no means the least I would like to thank Packt Publishing for giving this wonderful
opportunity to write this book and share my knowledge.
About the Reviewers
Yagna Narayana Dande is currently working as a Lead Soware Engineer in Tesng
at Komli Media, a digital adversing and technology company. She previously worked
as a QA Engineer at MapR Technologies. MapR Technologies focuses on engineering
game-changing, Map/Reduce-related technologies.
She has also worked as a Soware Engineer at Symantec, helping consumers and
organizaons secure and manage the informaon-driven world.
Mihai Vilcu has been involved in large-scale tesng projects for several years
and has exposure to top technologies for both automated and manual tesng
and funconal and non-funconal tesng. "Soware tesng excellence" is the
moo that drives Mihai's career.
Some of the applicaons covered by Mihai in his career are CRMs, ERPs, billing
plaorms, and rang, collecon and business process management applicaons.
Since soware plaorms are spread and intensely used in many industries in our
mes, Mihai has performed in elds such as telecom, banking, healthcare, soware
development, and more.
Readers are welcome to contact Mihai for quesons regarding tesng as well as requesng
his involvement in your projects. He can be contacted via his e-mail: mvilcu@mvfirst.ro
or directly on his website: www.mvfirst.ro.
www.PacktPub.com
Support les, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support les and downloads related to
your book.
Did you know that Packt oers eBook versions of every book published, with PDF and ePub les
available? You can upgrade to the eBook version at www.PacktPub.com and as a print book
customer, you are entled to a discount on the eBook copy. Get in touch with us at service@
packtpub.com for more details.
At www.PacktPub.com, you can also read a collecon of free technical arcles, sign up for a
range of free newsleers and receive exclusive discounts and oers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant soluons to your IT quesons? PacktLib is Packt's online digital book library.
Here, you can access, read and search across Packt's enre library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib
today and view nine enrely free books. Simply use your login credenals for immediate access.
Table of Contents
Preface 1
Chapter 1: Geng Started 5
Tesng and test automaon 6
TestNG 6
Features of TestNG 7
Downloading TestNG 8
Prerequisites 8
Installing TestNG onto Eclipse 8
Time for acon – installing TestNG onto Eclipse 9
Wring your rst TestNG test 13
The Java project 13
Time for acon – creang a Java project 13
Time for acon – creang your rst TestNG class 16
Running your rst test program 18
Time for acon – running tests through Eclipse 18
Summary 21
Chapter 2: Understanding testng.xml 23
About testng.xml 23
Creang a test suite 24
Time for acon – creang a test suite 24
Running testng.xml 26
Using command prompt 26
Time for acon – running testng.xml through the command prompt 26
Using Eclipse 28
Time for acon – execung testng.xml using Eclipse 28
Time for acon – conguring Eclipse to run a parcular TestNG XML le 29
Creang mulple tests 31
Time for acon – testng XML with mulple tests 31
Table of Contents
[ ii ]
Adding classes, packages, and methods to test 33
Sample project 34
Creang a test with classes 34
Time for acon – creang a test with classes 35
Creang a test using packages 36
Time for acon – creang a test with packages 36
Creang a test with methods 38
Time for acon – creang a test with methods 38
Creang a test with packages, classes, and methods 39
Time for acon – creang a test suite with package, class, and test method 40
Including and excluding 42
Include/exclude packages 42
Time for acon – test suite to include a parcular package 42
Time for acon – test suite to exclude a parcular package 43
Include/exclude methods 45
Time for acon – test suite to exclude a parcular method 45
Using regular expressions to include/exclude 46
Prerequisite – creang a sample project 46
Time for acon – using regular expressions for test 48
Summary 50
Chapter 3: Annotaons 51
Annotaons in TestNG 52
Before and Aer annotaons 53
Time for acon – running the Before and Aer annotaons 54
Time for acon – Before and Aer annotaon when extended 59
Test annotaon 62
Time for acon – using test annotaon on class 63
Disabling a test 64
Time for acon – disabling a test method 65
Excepon test 66
Time for acon – wring an excepon test 66
Time for acon – wring a excepon test verifying message 68
Time test 69
Time for acon – me test at suite level 70
Time for acon – me test at test method level 71
Parameterizaon of test 73
Parameterizaon through testng.xml 73
Time for acon – parameterizaon through testng.xml 73
Time for acon – providing oponal values 76
DataProvider 78
Time for acon – using Test annotaon on Class 79
Table of Contents
[ iii ]
Time for acon – DataProvider in dierent class 81
Summary 84
Chapter 4: Groups 85
Grouping tests 85
Time for acon – creang test that belong to a group 86
Running a TestNG group 87
Using Eclipse 88
Time for acon – running a TestNG group through Eclipse 88
Using the testng XML 89
Time for acon – running a TestNG group using the testng XML 89
Test that belong to mulple groups 91
Time for acon – creang a test having mulple groups 91
Including and excluding groups 93
Time for acon – including/excluding groups using the testng XML 93
Using regular expressions 95
Time for acon – using regular expressions in the testng XML 96
Default group 98
Time for acon – assigning a default group to a set of tests 98
Group of groups 100
Time for acon – running a TestNG group using the testng XML 101
Summary 103
Chapter 5: Dependencies 105
Dependency test 105
Test with single test method dependency 105
Time for acon – creang a test that depends on another test 106
Test that depends on mulple tests 107
Time for acon – creang a test that depends on mulple tests 108
Inherited dependency test 109
Time for acon – creang a test that depends on inherited tests 110
Dependent groups 112
Time for acon – creang a test that depends on a group 112
Depending on methods from dierent classes 113
Time for acon – depending on a method from a dierent class 114
Using regular expressions 115
Time for acon – using regular expressions 115
XML-based dependency conguraon 117
Simple group dependency 117
Time for acon – using simple dependency in XML 117
Mulgroup dependency 119
Time for acon – dening mulgroup dependency in XML 119
Table of Contents
[ iv ]
Using regular expressions for dening dependency 121
Time for acon – using regular expressions for dependency 121
Summary 124
Chapter 6: The Factory Annotaon 125
What is factory? 125
First factory program 125
Time for acon – rst factory test 126
Passing parameters to test classes 127
Time for acon – passing parameters to test classes 128
Using DataProvider along with the @Factory annotaon 129
Time for acon – using DataProvider with Factory 130
DataProvider or Factory 131
Time for acon – the DataProvider test 132
Time for acon – the Factory test 133
Dependency with the @Factory annotaon 135
Time for acon – dependency with the @Factory annotaon 135
Time for acon – running a dependency test sequenally 137
Summary 138
Chapter 7: Parallelism 139
Parallelism 140
A simple multhreaded test 140
Time for acon – wring rst parallel test 140
Running test methods in parallel 142
Time for acon – running test methods in parallel 142
Running test classes in parallel 144
Time for acon – running test classes in parallel 145
Running tests inside a suite in parallel 148
Time for acon – running tests inside a suite in parallel 148
Conguring an independent test method to run in mulple threads 151
Time for acon – running independent test in threads 151
Advantages and uses 153
Summary 154
Chapter 8: Using Build Tools 155
Build automaon 155
Advantages of build automaon 156
Dierent build tools available 156
Ant 156
Installing Ant 156
Using Ant 157
Time for acon – using Ant to run TestNG tests 157
Table of Contents
[ v ]
Dierent conguraons to be used with TestNG task 161
Maven 162
Installing Maven 162
Using Maven 163
Time for acon – using Maven to run TestNG tests 163
Dierent conguraons to be used with Maven 166
Summary 167
Chapter 9: Logging and Reports 169
Logging and reporng 169
Wring your own logger 170
Time for acon – wring a custom logger 170
Wring your own reporter 175
Time for acon – wring a custom reporter 175
TestNG HTML and XML report 177
Time for acon – generang TestNG HTML and XML reports 177
Generang a JUnit HTML report 180
Time for acon – generang a JUnit report 180
Generang a ReportNG report 182
Time for acon – generang a ReportNG report 183
ReportNG conguraon opons 186
Generang a Reporty-ng (former TestNG-xslt) report 187
Time for acon – generang a Reporty-ng report 187
Conguraon opons for Reporty-ng report 190
Summary 191
Chapter 10: Creang a Test Suite through Code 193
Running TestNG programmacally 193
Time for acon – running TestNG programmacally 194
Parameterizaon of tests 197
Time for acon – passing parameter values 197
Include and exclude 200
Include/exclude methods 200
Time for acon – including test methods 201
Include/exclude groups 204
Time for acon – including/excluding groups 204
Dependency test 207
Time for acon – conguring a dependency test 207
Summary 210
Chapter 11: Migrang from JUnit 211
Running your JUnit tests through TestNG 211
Time for acon – wring a JUnit test 212
Table of Contents
[ vi ]
Running your JUnit Tests through TestNG using the testng XML 214
Time for acon – running JUnit tests through TestNG 214
Running JUnit and TestNG tests together with TestNG XML 215
Time for acon – running JUnit and TestNG tests together 215
Running JUnit tests along with TestNG through Ant 217
Time for acon – running JUnit and TestNG tests through Ant 217
Migrang from JUnit to TestNG 220
Time for acon – converng a JUnit test to a TestNG test 221
Summary 224
Chapter 12: Unit and Funconal Tesng 225
Unit tesng with TestNG 225
Time for acon – unit tesng with TestNG 226
Asseron with TestNG 228
Mocking 228
Dierent mocking strategies 229
Mocking with TestNG 229
Jmock 229
Time for acon – using JMock with TestNG 230
Mockito 235
Time for acon – using Mockito 235
Funconal tesng 239
TestNG with Selenium 239
Time for acon – using Selenium with TestNG 240
Summary 245
Pop Quiz Answers 247
Index 251
Preface
Introduction
Currently, TestNG is the most widely used tesng framework in the soware industry.
It provides a lot of features over the convenonal JUnit framework and is used for
dierent kinds of tesng like unit, funconal, integraon tesng, and so on. This book
explains dierent features of TestNG with examples. You will learn about the basic
features as well as some of the advanced features provided by TestNG.
What this book covers
Chapter 1, Geng Started, explains TestNG and its advantages over other exisng
frameworks. It also explains how to install and run your rst TestNG test.
Chapter 2, Understanding testng.xml, explains the testng.xml le which is used to congure
the TestNG tests. It also explains dierent ways to create test suites by adding test packages,
test classes, and test methods to the respecve test suite, according to test needs.
Chapter 3, Annotaons, explains the various annotaons in TestNG and the dierent features
supported by using them.
Chapter 4, Groups, explains the grouping feature provided by TestNG and how you
can use it to include or exclude a group of tests in test execuon.
Chapter 5, Dependencies, explains the dependency feature provided by TestNG. You will
learn how test methods can depend upon another method or a group of methods.
Chapter 6, The Factory Annotaon, explains the Factory annotaon and how tests can be
created at runme based on a set of data. You will also learn about the dierence between
Factory and DataProvider annotaon and how they can be used together.
Preface
[ 2 ]
Chapter 7, Parallelism, explains a very important feature of TestNG which allows dierent
conguraons for dierent tests to be run in parallel.
Chapter 8, Using Build Tools, explains build automaon and its advantages. It also explains
the dierent build automaon tools available and how TestNG can be used along with them.
Chapter 9, Logging and Reports, explains about the default logging and report opons
available with TestNG. It also explains how to extend and write your own logging and
reporng framework above it.
Chapter 10, Creang a Test Suite through Code, explains the dierent ways to write and
congure TestNG tests through code without the need of an XML conguraon le.
Chapter 11, Migrang from JUnit, explains dierent ways to migrate to JUnit from TestNG
and things that need to be taken care of while migrang.
Chapter 12, Unit and Funconal Tesng, explains the unit and funconal tesng usage of
TestNG. It also explains the few mocking techniques to be used for Unit tesng and covers
the use of Selenium with TestNG for funconal tesng.
What you need for this book
Java JDK
Eclipse
Ubuntu/Linux or Windows
Basic knowledge of Java and tesng
Who this book is for
This book is for any Java developer who would like to improve their unit tests and would
like to do more with funconal, integraon, and API tesng. This book will also interest QA
guys who are exploring new unit tesng frameworks for their funconal automaon, API, or
integraon tesng needs.
Conventions
In this book, you will nd several headings appearing frequently.
To give clear instrucons of how to complete a procedure or task, we use:
Preface
[ 3 ]
Time for action – heading
1. Acon 1
2. Acon 2
3. Acon 3
Instrucons oen need some extra explanaon so that they make sense, so they are
followed with:
What just happened?
This heading explains the working of tasks or instrucons that you have just completed.
You will also nd some other learning aids in the book, including:
Pop quiz – heading
These are short mulple-choice quesons intended to help you test your own
understanding.
Have a go hero
These praccal challenges give you ideas for experimenng with what you have learned.
You will also nd a number of styles of text that disnguish between dierent kinds of
informaon. Here are some examples of these styles, and an explanaon of their meaning.
Code words in text, database table names, folder names, lenames, le extensions,
pathnames, dummy URLs, user input, and Twier handles are shown as follows: "The
previous XML denes a TestNG suite using the tag name suite. The name of the suite
is menoned using the name aribute (in this case First Suite)."
A block of code is set as follows:
<suite name="First Suite" verbose="1" >
<test name="First Test" >
<classes>
<class name="test.FirstTest" />
</classes>
</test>
</suite>
Preface
[ 4 ]
New terms and important words are shown in bold. Words that you see on the screen,
in menus or dialog boxes, for example, appear in the text like this: "Select the project
and then right-click on it to select New | File."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or may have disliked. Reader feedback is important for us to
develop tles that you really get the most out of.
To send us general feedback, simply send an e-mail to feedback@packtpub.com,
and menon the book tle via the subject of your message.
1
Getting Started
Testing is an important part of software development and holds a key position
in the software development life cycle. Testing can be of multiple types such as
unit, integration, functional, manual, automation, and so on; it's a huge list.
TestNG is one of the most popular testing, or test automation frameworks in
Java, which is widely used nowadays. This book will familiarize you with the
different features offered by TestNG and how to make best use of them.
In this chapter we'll cover the following topics:
Tesng and test automaon
Features of TestNG
Downloading TestNG
Installing TestNG onto Eclipse
Wring your rst test program
Running your rst test program
Geng Started
[ 6 ]
Testing and test automation
Tesng as you may know is the process of validang and verifying that a piece of soware
or hardware is working according to the way it's expected to work. Tesng is a very important
part of the soware development life cycle (SDLC) as it helps in improving the quality of the
product developed. There are mulple types and levels of tesng, for example, white-box,
black-box, unit, integraon, system, acceptance, performance, security, funconal,
non-funconal, and so on. Each of these types of tesng are done either manually
or through automaon, using automaon tools.
Test automaon, as the name suggests, refers to automang the tesng process. This
can be done for dierent tesng types and levels such as unit tesng, integraon tesng,
funconal tesng, and so on, through dierent means either by coding or by using tools.
Test automaon gives an advantage of running tests in numerous ways such as at regular
intervals or as part of the applicaon build. This helps in idenfying bugs at the inial phase
of development itself, hence reducing the product meline and improving the product
quality. It also helps in reducing the repeve manual tesng eort and allows manual
tesng teams to focus on tesng new features and complex scenarios.
TestNG
TestNG, where NG stands for "next generaon" is a test automaon framework inspired
by JUnit (in Java) and NUnit (in C#). It can be used for unit, funconal, integraon, and
end-to-end tesng. TestNG has gained a lot of popularity within a short me and is one
of the most widely used tesng frameworks among Java developers. It mainly uses Java
annotaons to congure and write test methods.
TestNG was developed by Cedric Beust. He developed it to overcome a deciency in JUnit.
A few of the features that TestNG has over JUnit 4 are:
Extra Before and Aer annotaons such as Before/Aer Suite and Before/Aer Group
Dependency test
Grouping of test methods
Multhreaded execuon
In-built reporng framework
So, let's get familiarized with TestNG. As I menoned earlier, TestNG is a tesng framework.
It is wrien in Java and can be used with Java as well as with Java-related languages such
as Groovy. In TestNG, suites and tests are congured or described mainly through XML
les. By default, the name of the le is testng.xml, but we can give it any other name
if we want to.
Chapter 1
[ 7 ]
TestNG allows users to do test conguraon through XML les and allows them to include
(or exclude) respecve packages, classes, and methods in their test suite. It also allows users
to group test methods into parcular named groups and to include or exclude them as part
of the test execuon.
Parameterizaon of test methods is very easy using TestNG and it also provides an easy
method of creang data-driven tests.
TestNG exposes its API which makes it easy to add custom funconalies or extensions,
if required.
Features of TestNG
Now that you are at least a lile familiarized with TestNG, let's go forward and discover more
about the features oered by TestNG. The following are a few of the most important features:
Mulple Before and Aer annotaon opons: TestNG provides mulple kinds
of Before/Aer annotaons for support of dierent setup and cleanup opons.
XML-based test conguraon and test suite denion: Test suites in TestNG are
congured mainly using XML les. An XML le can be used to create suites using
classes, test methods, and packages, as well as by using TestNG groups. This le is
also used to pass parameters to test methods or classes.
Dependent methods: This is one of the major features of TestNG where you can
tell TestNG to execute a dependent test method to run aer a given test method.
You can also congure whether the dependent test method has to be executed
or not in case the earlier test method fails.
Groups/group of groups: Using this feature you can assign certain test methods
into parcular named groups and tell TestNG to include or exclude a parcular
group in a test.
Dependent groups: Like dependent methods, this feature allows test methods
belonging to one group being dependent upon another group.
Parameterizaon of test methods: This feature helps users to pass parameter
values through an XML conguraon le to the test methods, which can then
be used inside the tests.
Data-driven tesng: TestNG allows users to do data-driven tesng of test methods
using this feature. The same test method gets executed mulple mes based on
the data.
Multhreaded execuon: This allows execuon of test cases in a multhreaded
environment. This feature can be used for parallel test execuon to reduce
execuon me or to test a multhreaded test scenario.
Geng Started
[ 8 ]
Beer reporng: TestNG internally generates an XML and HTML report by default
for its test execuon. You can also add custom reports to the framework if required.
Open API: TestNG provides easy extension of API, this helps in adding custom
extensions or plugins to the framework depending upon the requirement.
We will discuss these features in more detail in coming chapters.
Downloading TestNG
Before we can download and start using TestNG, there are certain prerequisites we need.
So, let's go ahead with the prerequisites rst.
Prerequisites
Before you start using TestNG please make sure that Java JDK5 or above is installed on
your system. Also make sure that JDK is set in the system path. In case JDK is not available
on your system, you can download it from the following link:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
TestNG can be downloaded, installed, and run in mulple ways as follows:
Using command line
As an Eclipse plugin
As an IntelliJ IDEA plugin
Using ANT
Using Maven
In case you just want to download the TestNG JAR, you can get it from the following URL:
http://testng.org/testng-6.8.zip
Installing TestNG onto Eclipse
Before we go forward with installing the TestNG plugin onto Eclipse, please make sure
you have Eclipse installed on your system. You can get the latest version of eclipse from
http://www.eclipse.org/downloads/. At the me of wring this book, I am
using Eclipse JEE Juno-SR1 version.
Chapter 1
[ 9 ]
Time for action – installing TestNG onto Eclipse
Let's start with the installaon process of TestNG onto Eclipse:
1. Open your Eclipse applicaon.
2. Go to Help | Install New Soware.
3. Click on the Add… buon next to the Work with text box.
Geng Started
[ 10 ]
4. Enter TestNG site into the Name box and enter URL http://beust.com/
eclipse into the Locaon box. Once done, click on the OK buon.
5. On clicking OK, TestNG update site will get added to Eclipse. The available soware
window will show the tools available to download under the TestNG site.
Chapter 1
[ 11 ]
6. Select TestNG and click on Next.
7. Eclipse will calculate the soware requirements to download the selected TestNG
plugin and will show the Install Details screen. Click on Next on the details screen.
Geng Started
[ 12 ]
8. Accept the License Informaon and click on Finish. This will start the download
and installaon of the TestNG plugin onto Eclipse.
9. In case you get the following warning window, click on the OK buon.
10. Once the installaon is complete, Eclipse will prompt you to restart it.
Click on Yes on the window prompt.
11. Once Eclipse is restarted, verify the TestNG plugin installaon by going to Window |
Preferences. You will see a TestNG secon under the preferences window.
Chapter 1
[ 13 ]
What just happened?
We have successfully installed the TestNG plugin into our Eclipse installaon. This will help us
in execung our TestNG tests or suite using Eclipse. Now we can go ahead and write our rst
TestNG test.
Writing your rst TestNG test
Before we write our rst TestNG test, we have to create a Java project in Eclipse to add our
TestNG test classes.
The Java project
A Java project is a place which contains Java source code and related les to compile
your program. It can be used to maintain your source code and related les for proper
management of the les. Let's create a Java project in Eclipse. If you already know
how to create a Java project in Eclipse, you can skip this secon.
Time for action – creating a Java project
Perform the following steps to create a Java project:
1. Open Eclipse.
2. Go to File | New | Other. A window with mulple opons will be shown.
3. Select Java Project as shown in the following screenshot and click on Next:
Geng Started
[ 14 ]
4. On the next screen, enter a Project name for a Java project, let's say
FirstProject, as shown in the following screenshot, and click on Finish:
This will create a new Java project in Eclipse.
5. Now go to Project | Properes. Select Java Build Path on the le-hand side on the
Properes window as shown in the following screenshot. This will display the build
path for the newly created project.
Chapter 1
[ 15 ]
6. Click on the Libraries tab and click on the Add Library... opon.
7. Select TestNG on the Add Library window as shown in the following screenshot
and click on Next:
8. Click on Finish on your next window. This will add the TestNG library to your
Eclipse project.
Geng Started
[ 16 ]
What just happened?
We have successfully created a new Java project in Eclipse and added a TestNG library to the
build path of the project. Now we can go ahead and add new test classes for adding TestNG
tests. Now let's create our rst TestNG test class for this newly created Java project.
Time for action – creating your rst TestNG class
Perform the following steps to create your rst TestNG class:
1. Go to File | New | Other. This will open a new Add wizard window in Eclipse.
2. Select TestNG class from the Add wizard window and click on Next.
3. On the next window click on the Browse buon and select the Java project where
you need to add your class.
Chapter 1
[ 17 ]
4. Enter the package name and the test class name and click on Finish.
This window also gives you an opon to select dierent annotaons while creang
a new TestNG class. If selected, the plugin will generate dummy methods for these
annotaons while generang the class.
This will add a new TestNG class to your project.
5. Write the following code to your newly created test class:
package test;
import org.testng.annotations.Test;
public class FirstTest {
@Test
Geng Started
[ 18 ]
public void testMethod() {
System.out.println("First TestNG test");
}
}
The preceding code contains a class named FirstTest, which has a test method
named testMethod, denoted by the TestNG annotaon @Test menoned before
the testMethod() funcon. The test method will print First TestNG test
when it is executed.
What just happened?
We have successfully added a new TestNG test class to the newly created Java project
in Eclipse. Now let's run the newly created test class through Eclipse.
Running your rst test program
Now we will learn about how to run the newly added test class through Eclipse as well
as about dierent opons available for running your tests.
Time for action – running tests through Eclipse
Perform the following steps to run tests through Eclipse:
1. Select the Java project in the Eclipse and go to Run | Run Conguraon.
Chapter 1
[ 19 ]
2. Select TestNG in the given opons and click on the New buon to create a
new conguraon.
3. TestNG plugin provides mulple opons for running your test cases as follows:
Class: Using this option you can provide the class name along with the
package to run only the said specific test class.
Method: Using this you can run only a specific method in a test class.
Groups: In case you would like to run specific test methods belonging to
a particular TestNG group, you can enter those here for executing them.
Package: If you would like to execute all the tests inside a package, you
can specify these in this box.
Suite: In case you have suite files in the form of testng.xml files, you
can select those here for execution.
Let's enter the conguraon name as FirstProject and select the newly
created class under the Class secon and click on Apply.
4. Now if you would like to run the newly created conguraon, just click on Run
aer clicking on Apply. This will compile and run the TestNG test class that we
have wrien. The result of the test execuon is displayed in the Console and
Results windows of Eclipse as shown in the following screenshot.
You can also run the test class by selecng it and then right-clicking on it,
selecng Run as from the menu, and then choosing TestNG Test.
Geng Started
[ 20 ]
Following is the results output on the Eclipse Console window for the test execuon:
Following is the results output on the TestNG Results window in Eclipse for the
test execuon:
Have a go hero
Run a parcular method of a test class through TestNG using the Run Conguraon
feature in Eclipse.
Chapter 1
[ 21 ]
Pop quiz – about TestNG
Q1. TestNG is a unit tesng framework.
1. True
2. False
Q2. Suites in TestNG are congured using:
1. The XML le
2. The HTML le
3. The CSV le
Summary
In this chapter we learned about TestNG, features oered by TestNG, installing the TestNG
plugin into Eclipse and wring and execung a TestNG test class through Eclipse. In the
next chapter, we will learn about testng.xml and how to dene test suites using XML.
2
Understanding testng.xml
In the previous chapter we had learned about TestNG, its features, how to
set it up and run it through Eclipse. In this chapter we will learn about testng.
xml, the main configuration file of TestNG used to define suites, tests, and
configure TestNG.
In this chapter we'll cover the following topics:
About testng.xml
Creang a test suite
Running testng.xml
Creang mulple tests in suite
Adding classes, packages, and method to tests
Including and excluding classes, packages, and methods in tests
About testng.xml
testng.xml is a conguraon le for TestNG. It is used to dene test suites and tests
in TestNG. It is also used to pass parameters to test methods, which we will discuss under
the Parameterizaon of test secon in Chapter 3, Annotaons.
testng.xml provides dierent opons to include packages, classes, and independent test
methods in our test suite. It also allows us to congure mulple tests in a single test suite
and run them in a multhreaded environment.
Understanding testng.xml
[ 24 ]
TestNG allows you to do the following:
Create tests with packages
Create tests using classes
Create tests using test methods
Include/exclude a parcular package, class, or test method
Use of regular expression while using the include/exclude feature
Store parameter values for passing to test methods at runme
Congure multhreaded execuon opons
In the following secons and chapters we will be discussing more about these features.
Creating a test suite
Let's now create our rst TestNG test suite using testng.xml. We will create a simple test
suite with only one test method.
Time for action – creating a test suite
Perform the following steps for creang a test suite:
1. Go to the Eclipse project that we created in the previous chapter.
2. Select the project and then right-click on it and select New | File.
3. Select the project in the File window.
Chapter 2
[ 25 ]
4. Enter text testng.xml in the File name secon, and click on Finish.
5. Eclipse will add the new le to your project and will open the le in the editor,
as shown in the following screenshot:
Note that the previous screen may look different in your Eclipse
depending upon the plugins that are installed in it.
6. Add the following snippet to the newly created tesntg.xml le and save it.
<suite name="First Suite" verbose="1" >
<test name="First Test" >
<classes>
<class name="test.FirstTest" />
</classes>
</test>
</suite>
The preceding XML denes a TestNG suite using the tag name suite. The name of the suite
is menoned using the name aribute (in this case First Suite).
It contains a test, declared using the XML tag test and the name of the test is given using
the name aribute. The test contains a class (test.FirstTest) to be considered for test
execuon which is congured using the classes and class tags as menoned in the XML
le. We will discuss these in more detail going forward.
Let's go ahead and learn how to run the previously created testng.xml le.
Understanding testng.xml
[ 26 ]
Running testng.xml
In the earlier secon we had created a testng.xml le but haven't yet veried it by running
it. In this secon we will learn how to run the testng.xml conguraon le. There are
mulple ways of running the testng.xml le as a TestNG suite.
Using command prompt
You can execute the testng.xml le through the command prompt. This also allows the
use of mulple testng.xml les to execute simultaneously through TestNG. Before running
a testng.xml suite through the command prompt, we need to compile our project code.
However, compilaon of project code using Java is out of the scope of this book and is not
covered. Hence, we will use the class les compiled by Eclipse. The code compiled by Eclipse
can be found under a folder named bin inside your Test Java project folder.
Downloading the example code
You can download the example code les for all Packt books you have
purchased from your account at http://www.packtpub.com. If you
purchased this book elsewhere, you can visit http://www.packtpub.
com/support and register to have the les e-mailed directly to you.
Time for action – running testng.xml through the command
prompt
Perform the following steps for running testng.xml through the command prompt:
1. Open the command prompt on your system.
2. Go to the Test Java project folder where the new testng.xml is created.
3. Type the following line.
java -cp "/opt/testng-6.8.jar:bin" org.testng.TestNG testng.xml
In the preceding command we are adding the TestNG JAR and the project compiled
code to the Java classpath by using the -cp opon of Java.
Here /opt/testng-6.8.jar is the path to the testng JAR where you had
downloaded it and it may be dierent for your system. Also, bin is the folder
containing the compiled code of the Java project. This can be found under the
Eclipse project, which is under consideraon. We will talk about compiling code
and running tests in later chapters of this book.
Here org.testng.TestNG consists of the main method that Java will use to
execute the testng.xml le, which is passed as an argument at the command line.
Chapter 2
[ 27 ]
4. Run the previous command line by pressing the Enter key. This will execute the
test suite menoned in the testng.xml le using TestNG. Aer execuon an
HTML report is generated by TestNG in a folder named test-output under
the same directory where you had run the command. The following is the HTML
test report generated by TestNG:
Following is the console output:
What just happened?
We have successfully created our rst testng.xml test suite and executed it using the
command prompt. In case you would like to execute mulple testng.xml les, you
can use the previous method by passing the other XML les as added arguments to
the command line. The following is a sample command:
java -cp "/opt/testng-6.8.jar:bin" org.testng.TestNG testng.xml testng1.
xml
TestNG will execute all the tests declared under these testng XML les.
Understanding testng.xml
[ 28 ]
TestNG also allows execung a parcular test from the testng.xml le. To execute a
parcular test from the testng XML le, use the opon -testnames at the command
line with comma-separated names of tests that need to be executed. The following is a
sample command:
java -cp "/opt/testng-6.8.jar:bin" org.testng.TestNG -testnames "Second
Test" testng.xml
The preceding command will execute a test with the name Second Test from testng.xml
if it exists in the dened suite.
Using Eclipse
As we had already learned about how to run the testng.xml le using the command
prompt, we will now learn how to run it using Eclipse. This is one of the methods which
will help us to verify our testng.xml le while modifying it.
Time for action – executing testng.xml using Eclipse
Perform the following steps for execung testng.xml using Eclipse:
1. Open Eclipse and go to the project where we have created the testng.xml le.
2. Select the testng.xml le, right-click on it, and select Run As | TestNG suite.
3. Eclipse will execute the XML le as TestNG suite and you can see the following
report in Eclipse:
The preceding window may not be shown by default in Eclipse aer
execuon and you may have to click on the window to see the results.
You can also use the Run Conguraon opon provided by Eclipse to customize your TestNG
tests in Eclipse. Let's learn how to congure Eclipse to run testng XML les.
Chapter 2
[ 29 ]
Time for action – conguring Eclipse to run a particular TestNG
XML le
Perform the following steps to congure Eclipse to run a parcular TestNG XML le:
1. On the top-bar menu of Eclipse, go to Run | Run Conguraons.
2. Select TestNG from the set of conguraons and click on the New Launch
Conguraon icon.
3. On the conguraon window give a name My Test to the conguraon.
4. Go to the Project secon, click on Browse and select your project on the
project window.
Understanding testng.xml
[ 30 ]
5. Now go to the Suite secon and click on Browse. Select the mytestng.xml
conguraon.
6. Click on Apply, and then click on Run. This will run the selected testng XML
conguraon le.
What just happened?
We have successfully learned to congure and execute the testng XML le using
Eclipse. The conguraon also provides the opon to select mulple testng XML
les and pass extra arguments to congure execuon. Arguments can be passed by
going to the Arguments tab and entering them in the Program Argument secon.
Let's now learn to create mulple test secons inside a testng XML le.
Chapter 2
[ 31 ]
Creating multiple tests
Earlier we had created a simple testng.xml le with a single test in a suite. TestNG allows you
to dene mulple test secons in a single suite. This helps you in segregang your tests and
creang dierent tests based on modules, features, type of test (integraon or unit), and so on.
Time for action – testng XML with multiple tests
Let's create a testng XML le with mulple tests and run it:
1. Open Eclipse and create a new project with the name MultiTest and with the
following structure:
2. Open the FirstTestClass.java le and add the following code snippet onto it:
package test.firstpackage;
import org.testng.annotations.Test;
public class FirstTestClass {
@Test
public void firstTest(){
System.out.println("First test method");
}
}
The preceding class contains one test method, which is annotated by the @Test
annotaon. We will be discussing this annotaon in more detail in our next chapter.
The test method prints a message onto the console upon execuon.
Understanding testng.xml
[ 32 ]
3. Open the SecondTestClass.java le and add the following code snippet to it:
package test.firstpackage;
import org.testng.annotations.Test;
public class SecondTestClass {
@Test
public void secondTest(){
System.out.println("Second test method");
}
}
4. Now open the testng.xml le and add the following snippet to it:
<suite name="Suite" verbose="1" >
<test name="FirstTest" >
<classes>
<class name="test.firstpackage.FirstTestClass" />
</classes>
</test>
<test name="SecondTest" >
<classes>
<class name="test.firstpackage.SecondTestClass" />
</classes>
</test>
</suite>
The XML le denes a suite with the name Suite. The suite contains two tests
with names FirstTest and SecondTest respecvely. These tests are congured
to execute separate classes test.firstpackage.FirstTestClass and test.
firstpackage.SecondTestClass.
When the XML le is executed as a suite in TestNG, each class is executed by a
separate test secon of a suite.
Chapter 2
[ 33 ]
5. Now run the testng.xml le using Eclipse. Once executed you will see the
following output generated in Eclipse:
What just happened?
We have successfully created a testng XML conguraon le with mulple test
secons and then ran it using TestNG. You can run these tests individually by the
dierent -testnames conguraon supported by TestNG as explained in the
Time for acon – running testng.xml through the command prompt secon.
Adding classes, packages, and methods to test
Earlier we learned about creang test suites, suites with mulple tests, and running them
through TestNG. Now we will learn how to create and congure suites to execute only the
tests belonging to a parcular class or a package or just a parcular test method.
In earlier examples you may have noced tests with a single class. In this secon we will
learn how to add mulple classes to a test.
Understanding testng.xml
[ 34 ]
Sample project
Before going ahead with creaon of test suite with classes, packages, and test methods,
we will need a sample project in place for dening test suites for test execuon. Let's
create a sample project rst:
1. Open Eclipse and create a new project with three packages, each package
containing two classes, as menoned in the following screenshot. Also, add
TestNG library to the project as menoned in Chapter 1, Geng Started.
2. Add the following two test methods to each class with the following code:
@Test
public void firstTest(){
System.out.println("First test method");
}
@Test
public void secondTest(){
System.out.println("Second test method");
}
These methods print messages First test method and Second test method
to the console when executed.
3. Save the project.
Now the project is created for wring our test suites.
Creating a test with classes
In this secon we will learn how to create and congure TestNG test suite using classes.
We will use the sample project created earlier and use it to write an example.
Chapter 2
[ 35 ]
Time for action – creating a test with classes
Perform the following steps to create a test with classes:
1. Open the sample project that we created earlier.
2. Add new le TestNG conguraon XML by name class-testng.xml to the project
with following content.
<suite name="Class Suite" verbose="1">
<test name="Test">
<classes>
<class name="test.firstpackage.FirstTestClass" />
<class name="test.secondpackage.FirstTestClass" />
<class name="test.thirdpackage.FirstTestClass" />
</classes>
</test>
</suite>
The preceding testng XML suite denes a test with three classes (one from each
package). To add a class to your test suite just use a combinaon of classes and
class tag as shown. Use the class tag with the aribute name having a value of
the class name along with the package name (for example, test.firstpackage.
FirstTestClass) to add a test class to your test.
3. Now run the preceding testng XML le as a TestNG suite through Eclipse.
You will see the following results in Eclipse:
Understanding testng.xml
[ 36 ]
As you can see in the previous screenshot, TestNG executes all the test methods
present inside the test class added to the test suite, and excludes all the other test
classes present in the project.
What just happened?
We have successfully created and executed a TestNG test suite by adding few test classes
to the suite. We can use mulple class tags as and when required under the classes tag
secon to add mulple test classes to the tests. Now let's go ahead and create a test with
only packages.
Creating a test using packages
In this secon we will learn how to create and congure TestNG test suite using project
packages. A package may contain one or many classes in it. Using this conguraon we
can include all the classes under a package or its subpackages to the test suite.
We will use the sample project created earlier and use it to write an example.
Time for action – creating a test with packages
Perform the following steps to create a test with packages:
1. Let's use the same sample project created earlier.
2. Add new le TestNG conguraon XML by name package-testng.xml to the
project with following content:
<suite name="Package Suite" verbose="1">
<test name="Package Test">
<packages>
<package name="test.firstpackage" />
<package name="test.secondpackage" />
</packages>
</test>
</suite>
The preceding testng XML suite denes a test with two packages (test.
firstpackage and test.secondpackage, respecvely) as you can see. To add a
package to your test suite just use a combinaon of the packages and package tag
as shown in the previous code. Use the package tag with the aribute name having
a value of the package name (for example, test.firstpackage) under the tag
packages to add packages to your tests.
Chapter 2
[ 37 ]
3. Now run the previous testng XML le as a TestNG suite. You will see the following
results in Eclipse:
As you can see in the previous screenshot TestNG executes all the test classes that are using
TestNG annotaons in them under the added packages of the test suite and excludes all the
other test classes present in other packages of the project.
What just happened?
We have successfully created and executed a TestNG test suite by adding test packages
to the suite. TestNG executes all the test methods inside the test classes present in the
packages. In case you want to add all the subpackages under a parcular package, you
can use .* at the end of the package name (as shown in the following code snippet).
<suite name="Package Suite" verbose="1">
<test name="Package Test">
<packages>
<package name="test.*" />
</packages>
</test>
</suite>
Understanding testng.xml
[ 38 ]
This will execute all the subpackages present under the package test.
Now let's go ahead and create a test by conguring it to execute only a parcular test method.
Creating a test with methods
In this secon we will learn how to create and congure the TestNG test suite by adding
specic test methods from test classes. Using this conguraon, we can add specic test
methods from the test classes to the test suite for including them as part of the test execuon.
We will use the sample project created earlier and use it to write an example.
Time for action – creating a test with methods
Perform the following steps to create a test with methods:
1. We will use the same sample project created earlier for dening a test suite.
2. Add a new le TestNG conguraon XML by name method-testng.xml to the
project with following content:
<suite name="Method Suite" verbose="1">
<test name="Method Test">
<classes>
<class name="test.firstpackage.FirstTestClass">
<methods>
<include name="firstTest" />
</methods>
</class>
</classes>
</test>
</suite>
The preceding testng XML suite denes a class that needs to be considered for
test execuon and the test method that needs to be included for execuon. To
add methods to your test suite we have to use the tags methods and include/
exclude under them to add or remove parcular methods from a test class.
Chapter 2
[ 39 ]
3. Now run the previous testng XML le as a TestNG suite. You will see the following
results in Eclipse:
What just happened?
We have successfully created a TestNG suite, considering only a parcular method from a
test class, and executed it. In case you would like to add more methods, you can use mulple
include tags menoning the name of the method that you want to include in the test
execuon. Let's go ahead and create a test suite with all the combinaons: package, class,
and test method in a single test.
Creating a test with packages, classes, and methods
In this secon we will learn how to create and congure the TestNG test suite by including
packages, classes, and test methods.
We will use the sample project created earlier and use it to write an example.
Understanding testng.xml
[ 40 ]
Time for action – creating a test suite with package, class, and
test method
Perform the following steps to create a test suite with package, class, and test method:
1. We will use the same sample project created earlier for dening a test suite.
2. Add a new le TestNG conguraon XML by name combine-testng.xml to
the project with following content:
<suite name="Combine Suite" verbose="1">
<test name="Combine Test">
<packages>
<package name="test.firstpackage" />
</packages>
<classes>
<class name="test.secondpackage.FirstTestClass" />
<class name="test.thirdpackage.FirstTestClass">
<methods>
<include name="firstTest" />
</methods>
</class>
</classes>
</test>
</suite>
The preceding testng XML suite denes a test with a package (test.
firstpackage), a parcular class (test.secondpackage.FirstTestClass),
and a parcular test method (firstTest under the class test.thirdpackage.
FirstTestClass) as part of the test suite.
Chapter 2
[ 41 ]
3. Now run the previous testng XML le as a TestNG suite. You will see the following
results in Eclipse:
What just happened?
We have successfully created a TestNG suite by adding a parcular package, class, and test
method to the test, and then executed it. This gives us the exibility of creang a test with
dierent packages, classes, and test methods depending upon the test requirement.
Understanding testng.xml
[ 42 ]
Including and excluding
TestNG provides the exibility to include or exclude tests while dening a test suite. This
helps in dening a test suite with a parcular set of tests. While dening the testng XML
conguraon le, we can use the include and exclude tags to include or exclude tests.
Let's create a few test suites to include and exclude parcular tests and execute them.
Include/exclude packages
You can use the TestNG feature of including and excluding to include and exclude certain
test packages from a set of tests. Let's create a few test suites by including and excluding
test package in a test.
Time for action – test suite to include a particular package
Perform the following steps to create a test suite and include a parcular package:
1. Let's take the sample project created earlier for our tests.
2. Create a testng XML le with name include-package-testng.xml in the
project. Add the following code to it:
<suite name="Include Package Suite" verbose="1">
<test name="Include Package Test">
<packages>
<package name="test.*">
<include name="test.secondpackage" />
</package>
</packages>
</test>
</suite>
The preceding test suite denes a test, which includes all subpackages of the test
package (dened by using regular expression test.*) and includes only a parcular
package from all the packages for test execuon. This is done by using the include
tag with the name aribute value as the package name that needs to be included
(that is, test.secondpackage). This informs TestNG to include classes belonging
to the included package for test execuon.
Chapter 2
[ 43 ]
3. Execute the previous XML le as a TestNG suite and check the results.
The following report will be shown on the Eclipse report window:
As you can see the results, TestNG has executed test methods from all the classes present
under the included package test.secondpackage and skipped the other test methods.
Time for action – test suite to exclude a particular package
Perform the following steps to create a test suite and exclude a parcular package:
1. Let's take the sample project created earlier for our tests.
2. Create a testng XML le with name exclude-package-testng.xml
in the project. Add the following code to it:
<suite name="Exclude Package Suite" verbose="1">
<test name="Exclude Package Test">
<packages>
<package name="test.*">
<exclude name="test.secondpackage" />
</package>
</packages>
</test>
</suite>
Understanding testng.xml
[ 44 ]
The preceding test suite denes a test by including all subpackages of the test
package (dened by using the regular expression test.*) and excluding only a
parcular package from all the packages for test execuon. This is done by using
the exclude tag with the name aribute value as the package name (that is, test.
secondpackage) that needs to be excluded. This informs TestNG to exclude classes
belonging to the package from test execuon.
3. Execute the previous XML le as a TestNG suite and check the results. The following
report will be shown on the Eclipse report window:
As you can see from the results, TestNG has executed test methods from all the classes
present under all the packages under the test package excluding those that belong to
test.secondpackage.
What just happened?
We have successfully created test suites by including and excluding packages from the
test execuon. This helps us in creang tests by including or excluding parcular packages.
Chapter 2
[ 45 ]
Include/exclude methods
The include/exclude feature can also be used for including and excluding test
methods. It even supports paern matching opons to include/exclude methods
using regular expressions.
Let's rst create a simple test suite by including and excluding some test methods,
and then we will create a test suite by using regular expressions for including and excluding.
Including a test method for test suite is the same as creang a test suite with test methods.
This was already covered earlier so I will go forward and tell you how to exclude a parcular
test method from a test suite.
Time for action – test suite to exclude a particular method
Perform the following steps to create a test suite and exclude a parcular method:
1. We will use the same project created earlier.
2. Add a new le TestNG conguraon XML named exclude-method-testng.xml
to the project with the following content:
<suite name="Exclude Method Suite" verbose="1">
<test name="Exclude Method Test">
<classes>
<class name="test.firstpackage.FirstTestClass">
<methods>
<exclude name="firstTest" />
</methods>
</class>
</classes>
</test>
</suite>
The preceding testng XML suite denes a class that needs to be considered for test
execuon and the test method that needs to be excluded from execuon. To exclude
a method from your test suite we have to use the tags methods and exclude
under them to exclude a parcular method from a test class.
Understanding testng.xml
[ 46 ]
3. Now run the previous testng XML le as a TestNG suite. You will see the following
results in Eclipse:
As you can see in the test report, TestNG excluded the said test method from test
execuon and executed the rest of the test methods from the respecve test class.
Using regular expressions to include/exclude
The include and exclude features of TestNG support the use of regular expressions
for including and excluding parcular test methods based on certain search names.
Let's go ahead and create a test suite using regular expressions.
Prerequisite – creating a sample project
Before we go forward with wring a test suite using a regular expression we need a
sample project. So, let's rst create a sample project for our test:
1. Create a new Java project in Eclipse with the following structure.
Chapter 2
[ 47 ]
2. Add the following code to the RegularExpClass le under the package test.
regularexppackage:
package test.regularexppackage;
import org.testng.annotations.Test;
public class RegularExpClass {
@Test
public void includeTestFirst(){
System.out.println("First include test method");
}
@Test
public void includeTestSecond(){
System.out.println("Second include test method");
}
@Test
public void excludeTestFirst(){
System.out.println("First exclude test method");
}
@Test
public void excludeTestSecond(){
System.out.println("Second exclude test method");
}
@Test
public void includeMethod(){
System.out.println("Include method");
}
@Test
public void excludeMethod(){
System.out.println("Exclude method");
}
}
The preceding code contains mulple test methods with dierent names, and we will use
these methods to learn about usage of regular expressions in the include and exclude
tags in TestNG.
Understanding testng.xml
[ 48 ]
Time for action – using regular expressions for test
Perform the following steps for using regular expressions for test:
1. We will use the sample project created earlier for regular expressions.
2. Add a new le TestNG conguraon XML named regexp-testng.xml to the
project with the following content:
<suite name="Regular Exp Suite" verbose="1">
<test name="Regular Exp Test">
<classes>
<class name="test.regularexppackage.RegularExpClass">
<methods>
<include name=".*Test.*" />
</methods>
</class>
</classes>
</test>
</suite>
The preceding testng XML suite is congured to consider only those test methods
from a parcular class whose name contains the word Test in it. The regular
expression is considered by use of .* before and aer the text.
3. Now run the previous testng XML le as a TestNG suite. You will see the following
results in Eclipse:
Chapter 2
[ 49 ]
As you can see in the test report TestNG has executed only those test methods whose
name contains the word Test in it. You can use the regular expression (.*) at the beginning
or end of a text to perform an ends-with and starts-with search, respecvely. This regular
expression can also be used with the exclude tag to exclude parcular test methods from
test execuon.
What just happened?
We have successfully created a TestNG suite to include and exclude parcular test methods
from a class. Also we have learned about how to use regular expressions and use a name-
based search to include and exclude a test method in a test based on the test method name.
Have a go hero
Having gone through the chapter, feel free to aempt the following:
Write a testng XML conguraon le to exclude all the methods that start with a
parcular text
Create a testng XML conguraon le to include all the subpackages in a package
Pop quiz – TestNG XML
Q1. Can we dene a mulple test inside a test suite inside a testng XML?
1. Yes
2. No
Q2. Which of the following opons should be used to execute a parcular test from a
testng XML test suite containing a mulple tests secon in it?
1. -test
2. -testnames
3. -testopts
Q3. Which of the following regular expressions should be used in TestNG for a regular search?
1. * (Star)
2. .* (Dot Star)
3. x ( X)
Understanding testng.xml
[ 50 ]
Summary
In this chapter, we learned about testng XML conguraon les of TestNG to
dene dierent tests using classes, packages, and test methods. We also learned
about how to include/exclude packages and test methods from a parcular test.
We looked at how to use regular expressions to add parcular packages and test
methods to the methods based on matching names.
In the next chapter we will learn about dierent annotaons provided by TestNG
and how to use them.
3
Annotations
In the previous chapter we had learned about the TestNG XML configuration
file, the different features it provides, and the different ways to create a TestNG
test suite.
In this chapter we will learn about TestNG annotations and the different
features supported through them. These are the base of TestNG and most
of the features are supported through their use of TestNG.
In this chapter we'll cover the following topics:
Annotaons in TestNG
Before and Aer annotaons
Test annotaon
Disabling a test
Excepon test
Time test
Parameterizaon of test
Passing parameters to the test methods
Using DataProvider for parameterized tests
Annotaons
[ 52 ]
Annotations in TestNG
Annotaon is a feature introduced in Java 5 and is used to add metadata (data about data)
to Java source code. This will allow you to add informaon to an exisng data object in your
source code. It can be applied for classes, methods, variables, and parameters. Annotaons
may aect the way dierent programs or tools use your source code. There are certain
predened set of annotaons dened in Java. For example, @Override, @Deprecated,
@SupressWarnings, and so on, but Java allows users to dene their own annotaons too.
TestNg makes use of the same feature provided by Java to dene its own annotaons and
build an execuon framework by using it. The following is a table containing informaon
about all the annotaons provided by TestNG and a brief descripon of them:
Annotation Description
@BeforeSuite or
@AfterSuite
The annotated method will be executed before and after
any tests declared inside a TestNG suite.
@BeforeTest or
@AfterTest
The annotated methods will be executed before and after
each test section declared inside a TestNG suite.
@BeforeGroups or
@AfterGroups
These annotations are associated with the groups feature
in TestNG.
BeforeGroups annotated method will run before any
of the test method of the specified group is executed.
AfterGroups annotated method will run after any of
the test method of the specified group gets executed.
For this method to be executed, the user has to mention
the list of groups this method belongs to using groups
attribute with the said annotation. You can specify more
than multiple groups if required.
@BeforeClass or
@AfterClass
BeforeClass annotated method is executed before
any of the test method of a test class.
AfterClass annotated method is executed after the
execution of every test methods of a test class are executed.
@BeforeMethod or
@AfterMethod
These annotated methods are executed before/after the
execution of each test method.
@DataProvider Marks a method as a data providing method for a test
method. The said method has to return an Object
double array (Object[ ][ ]) as data.
Chapter 3
[ 53 ]
Annotation Description
@Factory Marks a annotated method as a factory that returns an
array of class objects (Object[ ]). These class objects
will then be used as test classes by TestNG. This is used to
run a set of test cases with different values.
@Listeners Applied on a test class. Defines an array of test listeners
classes extending org.testng.ITestNGListener.
Helps in tracking the execution status and logging purpose.
@Parameters This annotation is used to pass parameters to a test
method. These parameter values are provided using the
testng.xml configuration file at runtime.
@Test Marks a class or a method as a test method. If used at class
level, all the public methods of a class will be considered as
a test method.
Before and After annotations
Before and Aer annotaons are mainly used to execute a certain set of code before
and aer the execuon of test methods. These are used to basically set up some variables
or conguraon before the start of a test execuon and then to cleanup any of these things
aer the test execuon ends.
TestNG provides ve dierent kinds of Before and Aer annotaon opons, each of which
can be used depending upon the test requirements. The following are the dierent before
and aer opons provided by TestNG:
@BeforeSuite/@AfterSuite
@BeforeTest/@AfterTest
@BeforeGroups/@AfterGroups
@BeforeClass/@AfterClass
@BeforeMethod/@AfterMethod
Let's try out an example containing all the preceding annotated methods and learn about
how and when they are executed.
Annotaons
[ 54 ]
Time for action – running the Before and After annotations
1. Perform the following steps to run the Before and Aer annotaons: Open Eclipse
and create a Java Project with following structure. Please make sure that TestNG
library is added to the build path of the project as menoned in Chapter 1,
Geng Started.
2. Add the following code to the TestClass.java le shown in the
previous screenshot:
package test.beforeafter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class TestClass {
/**
* Before suite method which is executed before
* starting of any of the test in the suite.
*/
@BeforeSuite
public void beforeSuite(){
System.out.println("Before Suite method");
}
/**
Chapter 3
[ 55 ]
* After suite method which gets executed after
* execution of all the tests in a suite.
*/
@AfterSuite
public void afterSuite(){
System.out.println("After Suite method");
}
/**
* Before Test method which gets executed before the first
* test-method mentioned in each test inside the 'test'
* tag in test suite.
/
@BeforeTest
public void beforeTest(){
System.out.println("Before Test method");
}
/**
* After Test method which gets executed after
* the last test-method
*/
@AfterTest
public void afterTest(){
System.out.println("After Test method");
}
/**
* Before Class method which gets executed before
* any of the test-methods inside a class.
*/
@BeforeClass
public void beforeClass(){
System.out.println("Before Class method");
}
/**
* After Class method which gets executed after
* all of the test-methods inside a class gets executed.
*/
@AfterClass
Annotaons
[ 56 ]
public void afterClass(){
System.out.println("After Class method");
}
/**
* Before group method gets executed before executing any of
* the tests belonging to the group as mentioned in the 'groups'
* attribute.
* The following method gets executed before execution of the
* test-method belonging to group "testOne".
*/
@BeforeGroups(groups={"testOne"})
public void beforeGroupOne(){
System.out.println("Before Group Test One method");
}
/**
* After group method gets executed after executing all the
* tests belonging to the group as mentioned in the 'groups'
* attribute.
* The following method gets executed after execution of the
* test-methods belonging to group "testOne".
*/
@AfterGroups(groups={"testOne"})
public void afterGroupOne(){
System.out.println("After Group Test One method");
}
/**
* Before group method gets executed before executing any of the
tests
* belonging to the group as mentioned in the 'groups' attribute.
* The following method gets executed before execution of the
* test-method belonging to group "testTwo".
*/
@BeforeGroups(groups={"testTwo"})
public void beforeGroupTwo(){
System.out.println("Before Group Test two method");
}
/**
* After group method gets executed after executing all the tests
* belonging to the group as mentioned in the 'groups' attribute.
* The following method gets executed after execution of the
* test-methods belonging to group "testTwo".
*/
@AfterGroups(groups={"testTwo"})
public void afterGroupTwo(){
Chapter 3
[ 57 ]
System.out.println("After Group Test two method");
}
/**
* Before method which gets executed before each test-method.
*/
@BeforeMethod
public void beforeMethod(){
System.out.println("Before Method");
}
/**
* After method which gets executed after each test-method.
*/
@AfterMethod
public void afterMethod(){
System.out.println("After Method");
}
/**
* Test-method which belongs to group "testOne".
*/
@Test(groups={"testOne"})
public void testOneMethod(){
System.out.println("Test one method");
}
/**
* Test-method which belongs to group "testTwo".
*/
@Test(groups={"testTwo"})
public void testTwoMethod(){
System.out.println("Test two method");
}
}
As you can see there are mulple Before and Aer annotaons dened in the
preceding test class. Preceding each one, you will also see a small detail about
each of the annotated methods along with the details of when they are executed.
3. Create a new testng.xml le to the project and add the following code onto it:
<suite name="First Suite" verbose="1" >
<test name="First Test" >
<classes>
<class name="test.beforeafter.TestClass" >
<methods>
<include name="testOneMethod"/>
</methods>
</class>
Annotaons
[ 58 ]
</classes>
</test>
<test name="Second Test" >
<classes>
<class name="test.beforeafter.TestClass" >
<methods>
<include name="testTwoMethod"/>
</methods>
</class>
</classes>
</test>
</suite>
The preceding testng.xml le contains two tests containing the same test
class but with dierent test methods.
4. Execute the preceding testng.xml le as a TestNG suite. You will be shown
the following results in the Console window:
You can see the sequence in which the Before and Aer methods are executed.
The BeforeGroups and AfterGroups of the respecve test method group are
called before and aer the respecve group test method is executed.
Chapter 3
[ 59 ]
What just happened?
We have successfully created a test class with all kinds of Before and Aer annotaons and
executed it using a testng.xml. We had learned from the previous example the sequence
in which each of the respecve before and aer test methods are executed.
The current example only contains Before and Aer annotaons that are present in the same
class. Lets learn the execuon ow when a class containing a Before and Aer annotaon is
extended by another class having another set of Before and Aer annotaons.
Time for action – Before and After annotation when extended
1. Open eclipse and create a Java project with a package structure as menoned
below. Make sure that you have added TestNG library to the build path.
2. Add the following code to the BaseClass.java le:
package test.beforeafter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
public class BaseClass {
@BeforeClass
public void beforeBaseClass(){
System.out.println("Parent Before Class method");
}
@AfterClass
public void afterBaseClass(){
System.out.println("Parent After Class method");
}
@BeforeMethod
Annotaons
[ 60 ]
public void beforeBaseMethod(){
System.out.println("Parent Before method");
}
@AfterMethod
public void afterBaseMethod(){
System.out.println("Parent After method");
}
}
The preceding class contains BeforeClass, AfterClass, BeforeMethod,
and AfterMethod annotated methods. Each of these methods prints a text
to the console when executed.
3. Add the following code to the TestClass.java le:
package test.beforeafter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestClass extends BaseClass{
@BeforeClass
public void beforeChildClass(){
System.out.println("Child Before Class method");
}
@AfterClass
public void afterChildClass(){
System.out.println("Child After Class method");
}
@BeforeMethod
public void beforeChildMethod(){
System.out.println("Child Before method");
}
@AfterMethod
public void afterChildMethod(){
System.out.println("Child After method");
}
Chapter 3
[ 61 ]
@Test
public void testMethod(){
System.out.println("Test method under TestClass");
}
}
The preceding test class extends the BaseClass le created earlier and also
contains certain methods having BeforeClass/AfterClass and BeforeMethod/
AfterMethod annotaons. It also contains the test method denoted by the Test
annotaon. All the methods print a sample text to the console when executed.
4. Add a testng.xml le to the project and add the following code to it:
<suite name="Inheritance Suite" verbose="1" >
<test name="Inheritance Test" >
<classes>
<class name="test.beforeafter.TestClass" />
</classes>
</test>
</suite>
The preceding testng.xml le denes a single test inside a suite with only one
class TestClass considered for test.
5. Execute the previously created testng.xml le as a TestNG suite. You will see
the following output in the Eclipse's Console window:
Annotaons
[ 62 ]
What just happened?
We have successfully seen an example of a test class which contains a Before/Aer
annotaon. We also executed a test class, where the base class that the test class extends,
also contains similar Before/Aer annotated methods. As you can see, the report output
of TestNG executes the parent class before annotated methods and then the child before
annotated methods. Aer annotated methods, the child class method is executed and
then the parent class.
This helps us to have a common before annotated methods across all test classes and have
specic Before/Aer annotated methods for each test class where ever required.
Test annotation
One of the basic annotaons of TestNG is the Test annotaon. This annotaon marks a
method or a class as part of the TestNG test. If applied at class level this annotaon will mark
all the public methods present inside the class as test methods for TestNG test. It supports
lot of aributes which you can use along with the annotaon, which will enable you to use
the dierent features provided by TestNG. The following is a list of aributes supported by
the Test annotaon:
Supported attributes Description
alwaysRun Takes a true or false value. If set to true this method will always
run even if its depending method fails.
dataProvider The name of the data provider, which will provide data for
data-driven testing to this method.
dataProviderClass The class where TestNG should look for the data-provider method
mentioned in the dataProvider attribute. By default its the
current class or its base classes.
dependsOnGroups Specifies the list of groups this method depends on.
dependsOnMethods Specifies the list of methods this method depends on.
description The description of this method.
enabled Sets whether the said method or the methods inside the said class
should be enabled for execution or not. By default its value is true.
expectedExceptions This attribute is used for exception testing. This attribute specifies
the list of exceptions this method is expected to throw. In case a
different exception is thrown.
groups List of groups the said method or class belongs to.
timeOut This attribute is used for a time out test and specifies the time
(in millisecs) this method should take to execute.
Chapter 3
[ 63 ]
We will learn about these aributes and how to use them in future secons in this chapter
or in future chapters. As we have already seen sample tests using the Test annotaon on
methods, we will skip it and learn on how we can use the Test annotaon on a class.
Time for action – using test annotation on class
1. Open Eclipse and create a sample Java project as shown in the following screenshot
with TestNG library added to its build path:
2. Add a new test class with the name TestClass under the test package and add
the following code to it:
package test;
import org.testng.annotations.Test;
@Test
public class TestClass {
public void testMethodOne(){
System.out.println("Test method one.");
}
public void testMethodTwo(){
System.out.println("Test method two.");
}
private void testMethodThree(){
System.out.println("Test method three.");
}
}
The preceding class contains three methods out of which two are public
methods and one is a private method. The class has been annotated with
the Test annotaon.
Annotaons
[ 64 ]
3. Select the preceding test class in Eclipse and run it as TestNG test. You will see
the following results in the TestNG Results window in Eclipse:
What just happened?
We have successfully run a class which is being annotated by a Test annotaon of TestNG.
As you can see from the results, only two methods out of the three methods of the class
were executed by TestNG. If a class is annotated by the Test annotaon, TestNG will
consider only the methods with public access modiers as test methods. All the methods
with other access modiers will be neglected by TestNG.
Disabling a test
There may be some scenarios where you may have to disable a parcular test or a set of
tests from geng executed. For example, consider a scenario where a serious bug exists
in a feature due to certain tests belonging to certain scenarios that cannot be executed.
As the issue has already been idened we may need to disable the said test scenarios
from being executed.
Disabling a test can be achieved in TestNG by seng the enable aribute of the Test
annotaon to false. This will disable the said test method from being executed as part
of the test suite. If this aribute is set for the Test annotaon at class level, all the public
methods inside the class will be disabled.
Lets go ahead and create a sample project to see how this feature works.
Chapter 3
[ 65 ]
Time for action – disabling a test method
1. Create a new class inside the package test with name the DisableTestClass
inside the same Java project created earlier.
2. Add the following code to the newly created class:
package test;
import org.testng.annotations.Test;
public class DisableTestClass {
@Test(enabled=true)
public void testMethodOne(){
System.out.println("Test method one.");
}
@Test(enabled=false)
public void testMethodTwo(){
System.out.println("Test method two.");
}
@Test
public void testMethodThree(){
System.out.println("Test method three.");
}
}
The preceding class contains three test methods out of which, two contain the
aribute enabled with the values true and false respecvely.
3. Select and run the previous class as TestNG test in Eclipse. You will see following
results in the Results window of TestNG in Eclipse:
Annotaons
[ 66 ]
What just happened?
We have successfully created test methods with a Test annotaon and used the aribute
enabled along with it. As you can see in the previous results, only two methods were
executed by TestNG. The method with aribute enabled value as false was ignored from
test execuon. By default the aribute value of enabled is true, hence you can see the test
method with name testMethodThree was executed by TestNG even when the aribute
value was not specied.
Exception test
While wring unit tests there can be certain scenarios where we need to verify that an
excepon is being thrown by the program during execuon. TestNG provides a feature to
test such scenarios by allowing the user to specify the type of excepons that are expected
to be thrown by a test method during execuon. It supports mulple values being provided
for vericaon. If the excepon thrown by the test is not part of the user entered list, the
test method will be marked as failed.
Let's create a sample test and learn how excepon test works in TestNG.
Time for action – writing an exception test
1. Create a new Java project with the following structure in Eclipse:
2. Create a new class with name ExceptionTest and add the following code to it:
package test.exception;
import java.io.IOException;
import org.testng.annotations.Test;
public class ExceptionTest {
@Test(expectedExceptions={IOException.class})
public void exceptionTestOne() throws Exception{
throw new IOException();
}
Chapter 3
[ 67 ]
@Test(expectedExceptions={IOException.class,
NullPointerException.class})
public void exceptionTestTwo() throws Exception{
throw new Exception();
}
}
The preceding class contains two test methods, each throwing one parcular
kind of excepon, exceptionTestOne throws IOException where as
exceptionTestTwo throws Exception. The expected excepon to validate
while running these tests is menoned using the expectedExceptions
aribute value while using the Test annotaon.
3. Select and run the preceding class as TestNG test in Eclipse. You will see following
results in the Results window of TestNG in Eclipse:
What just happened?
We have successfully created an excepon test and ran it. As you can see from the test
results, exceptionTestTwo was marked as failed by TestNG during execuon. The test
failed because the excepon thrown by the said method does not match the excepon
list provided in the expectedExceptions list. The value to this list takes the expected
excepons to be passed as class as shown in the code.
TestNG also supports mulple expected excepons to be provided for vericaon while
execung a parcular test, this is shown in the preceding class for exceptionTestTwo test
method. You can also verify a test based on the excepon message that was thrown by the
test. Let's learn how to write a excepon test based on the excepon message thrown.
Annotaons
[ 68 ]
Time for action – writing a exception test verifying message
1. Create a new class with the name ExceptionMessageTest inside the Java project
created in the earlier secon.
2. Add the following code to it:
package test.exception;
import java.io.IOException;
import org.testng.annotations.Test;
public class ExceptionMessageTest {
/**
* Verifies the exception message based on the exact error
message thrown.
*/
@Test(expectedExceptions={IOException.class},
expectedExceptionsMessageRegExp="Pass Message test")
public void exceptionMsgTestOne() throws Exception{
throw new IOException("Pass Message test");
}
/**
* Verifies the exception message using the regular exception.
* This test verifies that the exception message contains a
text "Message" in it.
*/
@Test(expectedExceptions={IOException.class},
expectedExceptionsMessageRegExp=".* Message .*")
public void exceptionMsgTestTwo() throws Exception{
throw new IOException("Pass Message test");
}
/**
* Verifies the exception message based on the exact error
message thrown.
* This is to show that TestNG fails a test when the exception
message does not match.
*/
@Test(expectedExceptions={IOException.class},
expectedExceptionsMessageRegExp="Pass Message test")
public void exceptionMsgTestThree() throws Exception{
throw new IOException("Fail Message test");
}
}
Chapter 3
[ 69 ]
The preceding class contains three test methods each throwing the same
excepon but with dierent error messages. Vericaon for each test is done
based on the excepon error message thrown by them using the aribute
expectedExceptionsMessageRegExp while using the Test annotaon.
3. Select and run the preceding class as TestNG test in Eclipse. You will see following
results in the Results window of TestNG in Eclipse:
What just happened?
We successfully created a sample program to verify a test based on the excepon message
thrown. We executed and veried the previous test based on the excepon message thrown
by each of them. The aribute expectedExceptionsMessageRegExp can only be used
with the use of expectedExceptions aribute. Regular expression can also be used to
verify the error message, this can be done using .*. Depending upon the posion of the
regular expression we can use it to do paern matching such as starts-with, contains, and
ends-with while verifying the excepon message.
Time test
While running tests there can be cases where certain tests get stuck or may take much more
me than expected. In such a case you may need to mark the said test case as fail and then
connue. TestNG allows user to congure a me period to wait for a test to completely
execute. This can be congured in two ways:
At suite level: This will be applicable for all the tests in the said TestNG test suite
At each test method level: This will be applicable for the said test method and will
override the me period if congured at the suite level
Let's go ahead and create a sample project to see how this feature works.
Annotaons
[ 70 ]
Time for action – time test at suite level
1. Open Eclipse and create a sample Java project with the structure shown in the
following screenshot:
2. Add a sample test class with name TimeSuite and add the following code to it:
package test.timetest;
import org.testng.annotations.Test;
public class TimeSuite {
@Test
public void timeTestOne() throws InterruptedException{
Thread.sleep(1000);
System.out.println("Time test method one");
}
@Test
public void timeTestTwo() throws InterruptedException{
Thread.sleep(400);
System.out.println("Time test method two");
}
}
The preceding test class contains two test methods which print a message onto to
the console on successful execuon. Both also contain the Thread.sleep method
which pause the test execuon depending upon the argument passed for the me
specied in milliseconds.
3. Add a testng.xml le to the project and put the following code to it:
<suite name="Time test Suite" time-out="500" verbose="1" >
<test name="Timed Test" >
<classes>
<class name="test.timetest.TimeSuite" />
</classes>
</test>
</suite>
Chapter 3
[ 71 ]
The preceding testng.xml contains a suite with a single test considering a test
class for test execuon. You'll noce that the suite tag contains a new aribute
named time-out which is set with a value 500. This aribute applies a me-out
period for test methods for the whole suite. That means if any test method in
the said suite takes more than the specied me period (in this case 500
milliseconds) to complete execuon it will be marked as failed.
4. Run the preceding testng.xml le as TestNG suite in Eclipse. You will see the
following test results in the Results window of TestNG in Eclipse:
What just happened?
As you can see for the test result, TestNG executed the said tests and failed the rst test
as the test took more me to execute than the me menoned in the time-out secon. This
feature is useful while doing me tesng and to recover from lock condions in multhreaded
execuon. Let's now go ahead and learn to set the meout at a test method level.
Time for action – time test at test method level
1. Add a new test class to the project created in the earlier secon under the
timetest package with the name TimeMethod:
2. Add the following code to it:
package test.timetest;
import org.testng.annotations.Test;
Annotaons
[ 72 ]
public class TimeMethod {
@Test(timeOut=500)
public void timeTestOne() throws InterruptedException{
Thread.sleep(1000);
System.out.println("Time test method one");
}
@Test
public void timeTestTwo() throws InterruptedException{
Thread.sleep(400);
System.out.println("Time test method two");
}
}
The preceding test class contains two test methods which print a message onto to
the console on successful execuon. Both also contain Thread.sleep method
which pauses the test execuon depending upon the argument passed for the me
specied in milliseconds. A me-out value 500 at test level is specied for test
method timeTestOne using the aribute timeOut while using Test annotaon
as shown in the preceding code.
3. Select the respecve test class and execute it as TestNG test using Eclipse. You will
see the following test results in the TestNG Results window in Eclipse:
Chapter 3
[ 73 ]
What just happened?
As you can see from the test result, TestNG executed the said tests and failed the rst test.
The test failed because the test took more me to execute than the me menoned in the
timeOut aribute of the Test annotaon. This helps in specifying a predened execuon
me limit for a specic method. The meout value menoned at a test method level always
takes precedence over the the me-out specied at test suite level.
Parameterization of test
One of the important features of TestNG is parameterizaon. This feature allows user to pass
parameter values to test methods as arguments. This is supported by using the Parameters
and DataProvider annotaons. There are mainly two ways through which we can provide
parameter values to test-methods:
Through testng XML conguraon le
Through DataProviders
Parameterization through testng.xml
If you need to pass some simple values such as String types to the test methods at
runme, you can use this approach of sending parameter values through TestNG XML
conguraon les. You have to use the Parameters annotaon for passing parameter
values to the test method.
Let's write a simple example of passing parameters to test methods through the XML
conguraon le.
Time for action – parameterization through testng.xml
1. Open Eclipse and create simple Java project with the following package structure.
Make sure that you have added TestNG library to the project build path.
Annotaons
[ 74 ]
2. Add a new Java class le with the name ParameterTest and copy the following
code to it:
package test.parameter;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ParameterTest {
/**
* Following method takes one parameter as input. Value of the
* said parameter is defined at suite level.
*/
@Parameters({ "suite-param" })
@Test
public void prameterTestOne(String param) {
System.out.println("Test one suite param is: " + param);
}
/**
* Following method takes one parameter as input. Value of the
* said parameter is defined at test level.
*/
@Parameters({ "test-two-param" })
@Test
public void prameterTestTwo(String param) {
System.out.println("Test two param is: " + param);
}
/**
* Following method takes two parameters as input. Value of the
* test parameter is defined at test level. The suite level
* parameter is overridden at the test level.
*/
@Parameters({ "suite-param", "test-three-param" })
@Test
public void prameterTestThree(String param,
String paramTwo) {
System.out.println("Test three suite param is: " + param);
System.out.println("Test three param is: " + paramTwo);
}
}
Chapter 3
[ 75 ]
The preceding class contains three test methods, each of them require a dierent
set of parameter values. The Parameters annotaon is menoned for each of the
tests with the name of the parameter that needs to be passed to the test method
at the me of the test execuon. The value of these parameters needs to be
menoned in the testng XML le that will be dened for suite denion.
3. Create a testng. xml conguraon le with name param-testng.xml
and copy the following code to it:
<suite name="Parameter test Suite" verbose="1">
<parameter name="suite-param" value="suite level
parameter" />
<test name="Parameter Test one">
<classes>
<class name="test.parameter.ParameterTest">
<methods>
<include name="prameterTestOne" />
</methods>
</class>
</classes>
</test>
<test name="Parameter Test two">
<parameter name="test-two-param" value="Test two
parameter" />
<classes>
<class name="test.parameter.ParameterTest">
<methods>
<include name="prameterTestTwo" />
</methods>
</class>
</classes>
</test>
<test name="Parameter Test three">
<parameter name="suite-param" value="overiding suite
parameter" />
<parameter name="test-three-param" value="test three
parameter" />
<classes>
<class name="test.parameter.ParameterTest">
<methods>
<include name="prameterTestThree" />
</methods>
</class>
</classes>
</test>
</suite>
Annotaons
[ 76 ]
The preceding XML le contains three tests in it, each explains a dierent way of
passing the parameters to the test methods. The parameter is declared in testng
XML le using the parameter tag. The name aribute of the tag denes name of
the parameter whereas the value aribute denes the value of the said parameter.
The tag can be used at suite level as well as at test level, as you can see from the
preceding XML le.
4. Run the preceding testng.xml as TestNG test suite. You will see the following
test results on the Console window:
What just happened?
We created a test class with mulple methods that accepts parameters from TestNG. The
parameter values are set at both suite and test level in the testng XML le. Any parameter
value dened at the test level will override the value of a parameter, with same name, if
dened at suite level. You can see this in test three for test method prameterTestThree.
TestNG also provides an opon to provide oponal values for a parameter, this value will be
used if parameter value is not found in the dened le.
Time for action – providing optional values
Perform the following steps to provide oponal values:
1. Create a new class le with the name OptionalTest inside the Java project
created earlier.
2. Copy the following code to the said Java le and save it.
package test.parameter;
import org.testng.annotations.Optional;
Chapter 3
[ 77 ]
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class OptionalTest {
@Parameters({"optional-value"})
@Test
public void optionTest(@Optional("optional value")
String value){
System.out.println("This is: "+value);
}
}
The preceding class le contains a single test method that takes one parameter
as input. The said test method on execuon prints the parameter value that is
passed onto the console using the System.out.println method. The Parameter
value is passed to the test method using the parameter named optional-value
from the XML le. An oponal value for the said parameter is dened using the
Optional annotaon against the said parameter.
3. Create a new testng XML le with name optional-testng.xml and copy the
following code to it:
<suite name="Optional test Suite" verbose="1">
<test name="Optional Test one">
<classes>
<class name="test.parameter.OptionalTest" />
</classes>
</test>
<test name="Optional Test two">
<parameter name="optional-value" value="passed from xml" />
<classes>
<class name="test.parameter.OptionalTest" />
</classes>
</test>
</suite>
The preceding XML le has two tests dened in it. No parameter is dened in the
rst test where as the second test declares a parameter named optional-value
in it. Both contain the same test class for test execuon.
Annotaons
[ 78 ]
4. Select the above testng XML le and run it as a TestNG suite. You will see the
following results in the Console window of Eclipse:
What just happened?
We have successfully created a test using Optional annotaon of TestNG. As you can see
from the previous test results, TestNG has passed the oponal value to the test method during
rst test execuon. This happened because TestNG was unable to nd a parameter named
optional-value in the XML le from the rst test. During the second test it found the
parameter value in the XML and passed the said value to the test method during execuon.
The parameter annotaon can be used for any of the Before/After, Factory, and Test
annotated methods. It can be used to inialize variables and use them in a class, test,
or may be for the whole test execuon.
DataProvider
One of the important features provided by TestNG is the DataProvider feature. It helps
the user to write data-driven tests, that means same test method can be run mulple
mes with dierent datasets. DataProvider is the second way of passing parameters
to test methods. It helps in providing complex parameters to the test methods as it is
not possible to do this from XML.
To use the DataProvider feature in your tests you have to declare a method annotated by
DataProvider and then use the said method in the test method using the dataProvider
aribute in the Test annotaon.
Lets write a simple example and learn how to use the DataProvider feature in our tests.
Chapter 3
[ 79 ]
Time for action – using Test annotation on Class
1. Open Eclipse and create a Java project with the structure shown in the
following screenshot:
2. Create a new Java class with the name SameClassDataProvider and copy
the following code to it:
package test.dataprovider;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class SameClassDataProvider {
@DataProvider(name = "data-provider")
public Object[][] dataProviderMethod() {
return new Object[][] { { "data one" }, { "data two" } };
}
@Test(dataProvider = "data-provider")
public void testMethod(String data) {
System.out.println("Data is: " + data);
}
}
The preceding test class contains a test method which takes one argument as
input and prints it to console when executed. A DataProvider method is also
available in the same class by using the DataProvider annotaon of TestNG.
The name of the said DataProvider method is menoned using the name aribute
of the DataProvider annotaon. The DataProvider returns a double Object class
array with two sets of data, data one and data two.
The DataProvider to provide parameter values to a test method is dened by
giving the name of the data provider using the dataProvider aribute while
using the Test annotaon.
Annotaons
[ 80 ]
3. Add a new testng xml le to said project with the name simple-testng.xml
and add the following code to it:
<suite name="DataProvider test Suite" verbose="1">
<test name="DataProvider Test">
<classes>
<class name="test.dataprovider.SameClassDataProvider" />
</classes>
</test>
</suite>
The preceding testng XML le denes a simple test suite with the said test
class created earlier.
4. Select the testng xml le in eclipse and run it as a TestNG suite. You will see
following test result in the Console window:
What just happened?
As you can see from the above test result the respecve test method in the class was
executed two mes. The execuon of the test method is dependent upon the number
of datsets passed by the DataProvider method, in this case as two dierent sets of
data were returned by the DataProvider, the test method was executed two mes.
It is mandatory for a DataProvider method to return the data in the form of double
array of Object class (Object [][]). The rst array represents a data set where as the
second array contains the parameter values.
In the current example the DataProvider method was wrien in the same class. TestNG
by default looks for the DataProvider method in the same class or in any of the base
classes. But if you want to put your DataProvider method in another class, you can do
so by making it a stac method and providing the name of the class containing it to TestNG.
Lets take a look at this and learn how it works.
Chapter 3
[ 81 ]
Time for action – DataProvider in different class
1. Open Eclipse and add two new classes with the names DataProviderClass
and TestClass to the Java project created earlier.
2. Add the following code to TestClass:
package test.dataprovider;
import org.testng.annotations.Test;
public class TestClass {
@Test(dataProvider = "data-provider",dataProviderClass=DataProvi
derClass.class)
public void testMethod(String data) {
System.out.println("Data is: " + data);
}
}
The preceding test class contains a test method which takes one argument
as input and prints it onto the console when executed. The DataProvider to
provide parameter values to a test method is dened by giving the name of the
DataProvider using the DataProvider aribute while using Test annotaon.
As the DataProvider method is in a dierent class, the class name to refer for geng
the DataProvider is provided to TestNG using the dataProviderClass aribute as
seen in the preceding code.
3. Add the following code to DataProviderClass:
package test.dataprovider;
import org.testng.annotations.DataProvider;
public class DataProviderClass {
@DataProvider(name="data-provider")
public static Object[][] dataProviderMethod(){
return new Object[][] { { "data one" }, { "data two" } };
}
}
The preceding class only contains the DataProvider method to provide data to a test
method. The method returns two sets of data when called.
Annotaons
[ 82 ]
4. Add a new testng XML le to said project with the name different-class-
testng.xml and add the following code to it:
<suite name="Different class test Suite" verbose="1">
<test name="Different class Test">
<classes>
<class name="test.dataprovider.TestClass" />
</classes>
</test>
</suite>
The preceding testng XML le denes a simple test suite with a single test class.
5. Select the testng XML le in Eclipse and run it as a TestNG suite. You will see the
following test result in the Console window:
What just happened?
As you can see from the above test results the test method was executed two mes
depending upon the data passed to it by DataProvider method. In this scenario the
DataProvider method was in a dierent class. In such a case the DataProvider has to be
declared stac so that it can be used by a test method in a dierent class for providing data.
Have a go hero
Having gone through the chapter, feel free to aempt the following:
Write an Excepon test to verify that the excepon message thrown starts
with a specic text
Write a test method which accepts two parameters out of which one of
them is oponal
Chapter 3
[ 83 ]
Pop quiz – annotations
Q1. How many dierent type of Before and Aer annotaons are provided by TestNG?
1. 3
2. 4
3. 5
Q2. Using which aribute with the Test annotaon you can disable a test method?
1. disableTest
2. enableTest
3. enabled
4. disabled
Q3. We can provide mulple excepons while verifying a excepon in a test.
1. True
2. False
Q4. The me for performing me test is provided in?
1. seconds
2. milliseconds
3. minutes
4. hours
Q5. Which annotaon has to be used to provide a parameter to a test method?
1. Parameterizaon
2. Parameter
3. Parameters
Q6. What kind of return value does a DataProvider method have to return in TestNG?
1. Object
2. Object[]
3. Object[][]
4. List<Object>
Annotaons
[ 84 ]
Summary
In this chapter we had learned about the dierent annotaons provided by TestNG.
We have covered how and in which sequence the Before and Aer annotaon is executed.
We have also learned about the Test annotaon and parameterizaon feature in TestNG.
Finally, we then covered with examples, the me test, excepon test, and disabling a test
features of TestNG.
In the next chapter we will talk about the grouping feature of TestNG using the test methods
that can be grouped into a named group.
4
Groups
In the previous chapter we learned about different annotations provided by
TestNG and how to use them. In this chapter we will cover the grouping of test
methods, which is one of the most important concepts of TestNG.
In this chapter we'll cover the following topics:
Grouping tests
Running tests in a group
Tests belonging to mulple groups
Including/excluding groups
Using regular expressions
Default group
Group of groups
Grouping tests
As we have menoned previously, grouping test methods is one of the most important features
of TestNG. In TestNG users can group mulple test methods into a named group. You can also
execute a parcular set of test methods belonging to a group or mulple groups. This feature
allows the test methods to be segregated into dierent secons or modules. For example, you
can have a set of tests that belong to sanity test where as others may belong to regression
tests. You can also segregate the tests based on the funconalies/features that the test
method veries. This helps in execung only a parcular set of tests as and when required.
Let's create a few tests that belong to a parcular group.
Groups
[ 86 ]
Time for action – creating test that belong to a group
Perform the following steps to create a test that belongs to a group:
1. Open Eclipse and create a Java project with the structure shown in the following
screenshot. Please make sure that the TestNG library is added to the build path
of the project as menoned in Chapter 1, Geng Started.
2. Create a new class with the name TestGroup under the test.groups package
and replace the following code in it:
package test.groups;
import org.testng.annotations.Test;
public class TestGroup {
@Test(groups={"test-group"})
public void testMethodOne(){
System.out.println("Test method one belonging to group.");
}
@Test
public void testMethodTwo(){
System.out.println("Test method two not belonging to group.");
}
@Test(groups={"test-group"})
public void testMethodThree(){
System.out.println("Test method three belonging to group.");
}
}
The preceding test class contains three test methods out of which two belong to a
group named test-group. A test method can be assigned to test-group using
the groups aribute while using the @Test annotaon as shown.
Chapter 4
[ 87 ]
3. Select the preceding test class in Eclipse and run it as a TestNG test. You will see the
following test result in the TestNG's Results window of Eclipse:
What just happened?
We have successfully created a test class, which contains certain test methods that belong to
a group. The preceding test execuon does not consider the group for execuon and hence
executes all the tests in the specied test class.
TestNG automacally creates a group when it is menoned inside the groups secon of the
@Test annotaon. These groups can then be used to execute the test methods that belong
to them. In the coming secon we will learn how to execute test methods that belong to a
parcular group.
Running a TestNG group
In the earlier secon we created a test class with certain test methods that belonged to a
test group. In this secon we will learn how to run such tests in dierent ways.
We can run test methods belonging to a certain group in mainly two ways:
Through Eclipse
Using the testng XML le
Groups
[ 88 ]
Using Eclipse
In this secon we will learn how to run test methods that belong to a specic group
using Eclipse.
Time for action – running a TestNG group through Eclipse
Perform the following steps to run a TestNG group through Eclipse:
1. Open Eclipse and go to Run | Run Conguraons.
2. Select TestNG from the list of available conguraons and click on the new
conguraon icon.
3. In the new conguraon window give a conguraon name, for example,
GroupTest.
4. Go to the Project secon and click on the Browse buon. Select the previously
created project that is GroupsProject:
5. Go to the Groups secon and click on the Browse buon. Select the group which
you would like to execute from the list, in this case it's test-group:
Chapter 4
[ 89 ]
6. Click on the Apply buon and then click on Run. The following results will be shown
in the TestNG's Results window of Eclipse:
What just happened?
We have successfully executed test methods that belonged to a parcular group using
the TestNG runner conguraon in Eclipse. You can also use the ulity to execute mulple
groups by selecng the respecve groups in the Browse secon. Normally it's beer to use
the TestNG-XML-based execuon to execute test methods that belong to a parcular group.
Using the testng XML
In this secon we will learn how to create a testng XML le to execute test methods that
belong to a parcular group. This method is the preferred and easy way to execute groups.
Also, these testng XML les can then be used with build tools to execute TestNG test suites.
Time for action – running a TestNG group using the testng XML
Perform the following steps to run a TestNG group using the testng XML:
1. Open Eclipse and create a new le with the name testng.xml in the previously
created project.
2. Add the following code to the said le:
<suite name="Time test Suite" verbose="1">
<test name="Timed Test">
<groups>
<run>
Groups
[ 90 ]
<include name="test-group" />
</run>
</groups>
<classes>
<class name="test.groups.TestGroup" />
</classes>
</test>
</suite>
The preceding XML le contains only one test inside a suite. This contains the
groups secon dened by using the groups tag as shown in the code. The run
tag represents the group that needs to be run. The include tag represents the
name of the group that needs to be executed.
3. Select the previously created testng XML le and run it as a TestNG suite.
You will see the following test results in the TestNG's Results window of Eclipse:
What just happened?
In the previous secon we successfully created a testng XML le that creates a test in the
said suite by including a group in it. This is done by including the said group inside the run
secon. The run secon is in turn part of the groups tag secon inside the test. TestNG will
look for test methods that belong to the said group under the class that is menoned in the
classes secon of the test. The user can also provide packages for the tests. TestNG will
search all the classes that are added to the test to include or exclude parcular test methods
that belong to parcular groups. Once found, these test methods will then be executed by
TestNG as a test suite.
Chapter 4
[ 91 ]
Test that belong to multiple groups
Earlier we learned about creang tests that belonged to a single group, but TestNG allows
test methods to belong to mulple groups also. This can be done by providing the group
names as an array in the groups aribute of the @Test annotaon. Let's create a sample
program with mulple groups to learn how it is done.
Time for action – creating a test having multiple groups
Perform the following steps to create a test having mulple groups:
1. Open Eclipse and create a new Java class le with the name MultiGroup under
the test.groups package in the previously created project.
2. Replace the exisng code with the following code and save the le:
package test.groups;
import org.testng.annotations.Test;
public class MultiGroup {
@Test(groups={"group-one"})
public void testMethodOne(){
System.out.println("Test method one belonging to group.");
}
@Test(groups={"group-one","group-two"})
public void testMethodTwo(){
System.out.println("Test method two belonging to both
group.");
}
@Test(groups={"group-two"})
public void testMethodThree(){
System.out.println("Test method three belonging to group.");
}
}
The preceding class contains three test methods. Two of the test methods belong to
one group each, where as one of the methods belongs to two groups, group-one
and group-two respecvely.
3. Create a new testng XML le with the name multi-group-testng.xml in the
said project.
Groups
[ 92 ]
4. Replace the exisng code with the following code:
<suite name="Multi Group Suite" verbose="1">
<test name="Group Test one">
<groups>
<run>
<include name="group-one" />
</run>
</groups>
<classes>
<class name="test.groups.MultiGroup" />
</classes>
</test>
<test name="Group Test two">
<groups>
<run>
<include name="group-two" />
</run>
</groups>
<classes>
<class name="test.groups.MultiGroup" />
</classes>
</test>
</suite>
The preceding testng XML suite contains two tests, each of them execung test
methods belonging to a parcular group.
5. Select the previous XML le and run it as a TestNG suite. The following results
will be shown on the Results window of TestNG:
Chapter 4
[ 93 ]
What just happened?
We have successfully created a test method, which belongs to mulple groups and can
be executed successfully. As you can see in the previous test result, testMethodTwo was
executed in both the tests of the test suite. This is because it belongs to both of the groups
whose test methods are executed by TestNG.
TestNG allows a test method to belong to mulple groups. There is no limit on number of
groups that a test may belong to. To assign a test method to mulple groups just provide
the names of groups as comma-separated values to the groups aribute of the @Test
annotaon as shown in the previous example.
Including and excluding groups
TestNG also allows you to include and exclude certain groups from test execuon. This helps
in execung only a parcular set of tests and excluding certain tests. A simple example can
be when a feature is broken and you need to exclude a xed set of tests from execuon since
these test will fail upon execuon. Once the feature is xed you can then verify the feature
by just execung the respecve group of tests.
Let's create a sample program and learn how to exclude a group of tests.
Time for action – including/excluding groups using the
testng XML
Perform the following steps to include/exclude groups using the testng XML:
1. Open Eclipse and create a new Java le with the name ExcludeGroup under the
test.groups package in the previously created project.
2. Replace the exisng code in the le with the following code:
package test.groups;
import org.testng.annotations.Test;
public class ExcludeGroup {
@Test(groups={"include-group"})
public void testMethodOne(){
System.out.println("Test method one belonging to group.");
}
@Test(groups={"include-group"})
public void testMethodTwo(){
Groups
[ 94 ]
System.out.println("Test method two belonging to a group.");
}
@Test(groups={"include-group","exclude-group"})
public void testMethodThree(){
System.out.println("Test method three belonging to two
groups.");
}
}
The preceding class contains three test methods that print a message onto console
when executed. All the three methods belong to a group include-group whereas
the testMethodThree method also belongs to the group exclude-group.
3. Create a new testng XML le with the name exclude-group-testng.xml in
the same project.
4. Replace any exisng code with the following code:
<suite name="Exlude Group Suite" verbose="1">
<test name="Exclude Group Test">
<groups>
<run>
<include name="include-group" />
<exclude name="exclude-group" />
</run>
</groups>
<classes>
<class name="test.groups.ExcludeGroup" />
</classes>
</test>
</suite>
The preceding XML contains a simple test in which the group include-group is
included in the test using the include XML tag and the group exclude-group
is being excluded from the test execuon by using the exclude tag.
Chapter 4
[ 95 ]
5. Select the previous testng XML le and run it as a TestNG suite. The following
results will be shown on the Results window of TestNG:
What just happened?
As you can see from the previous test results TestNG executed two methods from
the group include-group and excluded the third method that belonged to the group
exclude-group, which was excluded from the test execuon. If a test method belongs
to both included and excluded group, the excluded group takes the priority and the test
method will be excluded from the test execuon.
You can have as many include and exclude groups as you want while creang a test suite
in TestNG.
Using regular expressions
While conguring your tests for including or excluding groups, TestNG allows the user to
use regular expressions. This is similar to including and excluding the test methods that
we covered earlier. This helps users to include and exclude groups based on a name search.
Let's create a sample program and learn how to use regular expressions while including
and excluding groups.
Groups
[ 96 ]
Time for action – using regular expressions in the testng XML
Perform the following steps to use regular expressions in the testng XML:
1. Open Eclipse and create a new Java le with the name RegularExpressionGroup
under the test.groups package in the previously created project.
2. Replace the exisng code in the le with the following code:
package test.groups;
import org.testng.annotations.Test;
public class RegularExpressionGroup {
@Test(groups={"include-test-one"})
public void testMethodOne(){
System.out.println("Test method one");
}
@Test(groups={"include-test-two"})
public void testMethodTwo(){
System.out.println("Test method two");
}
@Test(groups={"test-one-exclude"})
public void testMethodThree(){
System.out.println("Test method three");
}
@Test(groups={"test-two-exclude"})
public void testMethodFour(){
System.out.println("Test method Four");
}
}
The preceding class contains four test methods that print a message onto console
when executed. All of the test methods belong to a test group.
3. Create a new testng XML le with the name regexp-group-testng.xml in the
same project.
4. Replace any exisng code with the following code:
<suite name="Regular Exp. Group Suite" verbose="1">
<test name="Regular Exp. Test">
<groups>
<run>
Chapter 4
[ 97 ]
<include name="include.*" />
<exclude name=".*exclude" />
</run>
</groups>
<classes>
<class name="test.groups.RegularExpressionGroup" />
</classes>
</test>
</suite>
The preceding XML contains a simple test in which all the groups with a name
starng with include are included, whereas all the groups with name ending
with exclude are excluded from your test execuon.
5. Select the previous testng XML le and run it as TestNG suite. The following results
will be shown on the Results window of TestNG:
What just happened?
As you can see from the previous test results, TestNG executed two methods that belong
to groups with a name starng with include and excluded the test methods that belonged
to groups with names ending with exclude.
To use regular expressions to include and exclude groups you have to use .* for matching
names. In the previous example you can see the use of regular expression to search groups,
which starts and ends with a certain string. We can also use it for searching groups that
contains a certain string in their names by using the expression at start and end of the
search string (for example, .*name.*).
Groups
[ 98 ]
Default group
Somemes we may need to assign a default group to a set of test methods that belong to
a class. This can be achieved by using the @Test annotaon at class level and dening the
default group in the said @Test annotaon. This way all the public methods that belong
to the said class will automacally become TestNG test methods and become part of the
said group.
Let's write an example and learn how it works.
Time for action – assigning a default group to a set of tests
Perform the following steps to assign a default group to a set of tests:
1. Open Eclipse and create a new Java le with the name DefaultGroup under
the test.groups package in the previously created project.
2. Replace the exisng code in the le with the following code:
package test.groups;
import org.testng.annotations.Test;
@Test(groups={"default-group"})
public class DefaultGroup {
public void testMethodOne(){
System.out.println("Test method one.");
}
public void testMethodTwo(){
System.out.println("Test method two.");
}
@Test(groups={"test-group"})
public void testMethodThree(){
System.out.println("Test method three.");
}
}
The preceding class contains three methods that print a message onto console
when executed. All of the methods are considered as test methods by the use
of the @Test annotaon on the class. All of the methods belong to the group
default-group by menoning the group name at the class level. One of the
test methods also belong to the group test-group, this is done by using the
@Test annotaon at the method level as shown in the preceding code.
Chapter 4
[ 99 ]
3. Create a new testng XML le with the name default-group-testng.xml
in the same project.
4. Replace any exisng code with the following code:
<suite name="Default Group Suite" verbose="1">
<test name="Default Group Test one">
<groups>
<run>
<include name="default-group" />
</run>
</groups>
<classes>
<class name="test.groups.DefaultGroup" />
</classes>
</test>
<test name="Default Group Test two">
<groups>
<run>
<include name="test-group" />
</run>
</groups>
<classes>
<class name="test.groups.DefaultGroup" />
</classes>
</test>
</suite>
The preceding XML contains two separate tests, which execute two separate groups,
default-group and test-group respecvely. Both tests consider the same test
class to search for the test method that belongs to the group.
Groups
[ 100 ]
5. Select the previous testng XML le and run it as a TestNG suite.
The following results will be shown on the Results window of TestNG:
What just happened?
As you can see from the previous test results, TestNG executed all the test methods
of the class when the default-group tests were executed in the rst test. Whereas,
in the second test, only one method that belongs to the group test-group was executed.
This feature helps in assigning a default group to a set of tests.
This has to be used carefully as the use of the @Test annotaon at class level enables all
the public methods of the class to be considered as test methods.
Group of groups
TestNG allows users to create groups out of exisng groups and then use them during
the creaon of the test suite. You can create new groups by including and excluding
certain groups and then use them.
Let's create a sample test program and learn how to create group of groups
called MetaGroups.
Chapter 4
[ 101 ]
Time for action – running a TestNG group using the testng XML
Perform the following steps to run a TestNG group using the testing XML:
1. Let's use the exisng test class RegularExpressionGroup that was created
earlier under the Using regular expressions secon for this sample.
2. Create a new testng XML le with the name groupofgroup-testng.xml
under the same project which we created earlier.
3. Replace any exisng code with the following code and save it:
<suite name="Group of group Suite" verbose="1">
<test name="Group of group Test">
<groups>
<define name="include-group">
<include name="include-test-one" />
<include name="include-test-two" />
</define>
<define name="exclude-group">
<include name="test-one-exclude" />
<include name="test-two-exclude" />
</define>
<run>
<include name="include-group" />
<exclude name="exclude-group" />
</run>
</groups>
<classes>
<class name="test.groups.RegularExpressionGroup" />
</classes>
</test>
</suite>
The preceding XML contains one test in it. Two groups of groups have been dened
inside the test, and then these groups are used for test execuon. The MetaGroup is
created using the define tag inside the groups tag as shown in the previous code.
The name of the new group is dened using the name aribute under the define
tag. Groups are included and excluded from the new group by using the include
and exclude tags.
Groups
[ 102 ]
4. Select the previous testng XML le and run it as a TestNG suite.
The following results will be shown on the Results window of TestNG:
What just happened?
As you can see in the previous test results, TestNG executed only two methods, as
menoned in the included-group group and excluded the test methods that belong
to excluded-group. You can dene as many groups of groups as you want. This feature
is helpful in creang specic groups for regression, sanity, and module-wise tesng.
Have a go hero
Having gone through the chapter, feel free to aempt the following:
Write a sample testng XML, which will run all the groups that contains a parcular
text in their names
Create a sample testng XML, which uses regular expressions for including and
excluding groups, for a group of groups
Pop quiz – groups
Q1. Which aribute has to be used with the @Test annotaon to assign a group to
a test method?
1. groups
2. group
3. list-group
Chapter 4
[ 103 ]
Q2. Can we assign a default group to all the test methods in a class?
1. Yes
2. No
Q3. Can we use regular expressions for including and excluding groups in a test?
1. Yes
2. No
Q4. Which of the following is the correct format to search for group that contains
a text string?
1. .*test
2. test.*
3. .*test.*
4. *test*
Summary
In this chapter we have learned about the grouping of tests funconality provided by
TestNG. As we can see this feature helps us in organizing our test execuon by grouping
tests into mulple secons based on feature, type of test, and so on.
We can create as many groups as we want in TestNG and include and exclude these
groups in our tests based on the test requirement. Support of regular expressions and
the creaon of a group from other groups helps in including or excluding mulple groups
from the test execuon.
In the next chapter we will cover the dependency feature provided by TestNG. This
feature helps in dening a dependency of a test method or a group of test methods
on other test methods or a group. This gives the user a lot of power to congure or
control the execuon ow.
5
Dependencies
In the previous chapter we learned about grouping of tests which allows users
to group the tests into specific named groups. In this chapter we will learn
about the dependency feature in TestNG. Dependency allows users of TestNG
to specify a dependency method or a dependency group for a test method.
In this chapter we'll cover the following topics:
Dependency test
Wring a mulple dependency test
Dependency on group
Using regular expressions
Dening dependency through XML
Dependency test
As said earlier dependency is a feature in TestNG that allows a test method to depend on
a single or a group of test methods. This will help in execung a set of tests to be executed
before a test method. Method dependency only works if the depend-on-method is part of
the same class or any of the inherited base class (that is, while extending a class).
Test with single test method dependency
To start with, dependency in TestNG lets you create a sample test method that depends on
another test method of the same class.
Dependencies
[ 106 ]
Time for action – creating a test that depends on another test
Perform the following steps to create a test that depends on another test:
1. Open Eclipse and create a Java project with the following structure. Please make
sure that the TestNG library is added to the build path of the project as menoned
in Chapter 1, Geng Started.
2. Create a new package named method under the exisng test.depends package.
3. Create new class named SimpleDependencyTest under the test.depends.
method package and replace the following code in it:
package test.depends.method;
import org.testng.annotations.Test;
public class SimpleDependencyTest {
@Test(dependsOnMethods={"testTwo"})
public void testOne(){
System.out.println("Test method one");
}
@Test
public void testTwo(){
System.out.println("Test method two");
}
}
The preceding test class contains two test methods which print a message name
onto the console when executed. Here, test method testOne depends on test
method testTwo. This is congured by using the aribute dependsOnMethods
while using the Test annotaon as shown is the preceding code.
Chapter 5
[ 107 ]
4. Select the above test class in Eclipse and run it as TestNG test. You will see
the following test result in the Console window of Eclipse:
What just happened?
We successfully created a test class that contains a test method that depends upon
another test method. In the above test result you can see the message Test method
two printed before the Test method one message. This shows that the testOne
method got executed aer testTwo as it depends on testTwo.
The dependency on a test method is congured for a test by providing the dependent
test method name to the aribute dependsOnMethods while using the Test annotaon,
as menoned in the previous sample code.
Test that depends on multiple tests
Somemes it may be required for a test method to depend upon mulple other methods.
This feature is very well supported by TestNG as part of the dependency support. Let's create
a sample program and see how to create a test with mulple dependency.
Dependencies
[ 108 ]
Time for action – creating a test that depends on multiple tests
1. Create a new class named MultiDependencyTest under the test.depends.
method package and replace the following code in it:
package test.depends.method;
import org.testng.annotations.Test;
public class MultiDependencyTest {
@Test(dependsOnMethods={"testTwo","testThree"})
public void testOne(){
System.out.println("Test method one");
}
@Test
public void testTwo(){
System.out.println("Test method two");
}
@Test
public void testThree(){
System.out.println("Test method three");
}
}
The preceding test class contains three test methods which print a
message name onto the console when executed. Here test method testOne
depends on test methods testTwo and testThree. This is congured by using
the aribute dependsOnMethods while using the Test annotaon as shown in
the preceding code.
Chapter 5
[ 109 ]
2. Select the above test class in Eclipse and run it as TestNG test. You will see the
following test result in the Console window of Eclipse.
What just happened?
We successfully created a test class that contains a test method that depends upon mulple
test methods. By looking at the console message we can see that methods testTwo and
testThree got executed before testOne.
The dependency on mulple test methods is congured for a test by providing comma
separated dependent test method names to the aribute dependsOnMethods while
using the Test annotaon as menoned in the preceding sample code.
Inherited dependency test
Till now we have seen samples in which the dependent test methods were part of the
same class. As I said earlier, dependency on test methods can only be menoned for test
methods that belong to the same class or any of the inherited base classes. In this secon
we will see how TestNG executes the test methods when the dependent methods are part
of the inherited base class.
Dependencies
[ 110 ]
Time for action – creating a test that depends on inherited tests
1. Create a new class named InheritedTest under the test.depends.method
package and replace the following code in it:
package test.depends.method;
import org.testng.annotations.Test;
public class InheritedTest extends SimpleDependencyTest{
@Test(dependsOnMethods={"testOne"})
public void testThree(){
System.out.println("Test three method in Inherited test");
}
@Test
public void testFour(){
System.out.println("Test four method in Inherited test");
}
}
The preceding test class contains two test methods which print a message name
onto the console when executed. Here test method testThree depends on test
method testOne. This is congured by using the aribute dependsOnMethods
while using the Test annotaon as shown in the preceding code.
Following is the code of the SimpleDependencyTest class:
package test.depends.method;
import org.testng.annotations.Test;
public class SimpleDependencyTest {
@Test(dependsOnMethods={"testTwo"})
public void testOne(){
System.out.println("Test method one");
}
@Test
public void testTwo(){
System.out.println("Test method two");
}
}
Chapter 5
[ 111 ]
The preceding class also contains two test methods which print a message to the
console. As you can see, the testOne method in the preceding class depends on
the testTwo method.
2. Select the preceding test class in Eclipse and run it as TestNG test. You will see
the following test result in the Console window of Eclipse:
What just happened?
We successfully created a test class that contains a test method that depends upon the
parent class test method. As you can see from the test results the sequence of execuon
is testFour, testTwo, testOne, and lastly, testThree. As testThree depends on
testOne and on testTwo, TestNG executes all the test methods based on the dependency
and nally the respecve test method. TestNG by default executes methods based on the
ascending order of their names, so in this case, it executes testFour rst because it comes
at the top in the current list of the test methods, then when it encounters the dependency
of testThree, it executes its dependent methods and then the said method itself.
Using the dependency feature, you can also make certain methods run sequenally by
conguring the dependency accordingly.
Dependencies
[ 112 ]
Have a go hero
Having gone through the chapter, feel free to aempt the following:
Create a test class which contains three test methods and congure dependency
for these test methods in such a way that all of them get executed in a parcular
sequenal order.
Create a test class that is inherited from another test class and has overriding
test methods in it. Congure one of the test methods such that it depends on
the overriding test method.
Dependent groups
Similar to dependent methods TestNG also allows test methods to depend on groups. This
makes sure that a group of test methods get executed before the dependent test method.
Time for action – creating a test that depends on a group
1. Create a new package named groups under the test.depends package in the
earlier project.
2. Create a new class named SimpleGroupDependency under the test.depends.
groups package and replace the following code in it:
package test.depends.groups;
import org.testng.annotations.Test;
public class SimpleGroupDependency {
@Test(dependsOnGroups={"test-group"})
public void groupTestOne(){
System.out.println("Group Test method one");
}
@Test(groups={"test-group"})
public void groupTestTwo(){
System.out.println("Group test method two");
}
@Test(groups={"test-group"})
public void groupTestThree(){
System.out.println("Group Test method three");
}
}
Chapter 5
[ 113 ]
The preceding test class contains three test methods which print a message onto the
console when executed. Two of the test methods belong to a group named test group
whereas the third method named groupTestOne depends on the group test group.
The dependency on the group is congured using the aribute dependsOnGroups
while using the Test annotaon, as shown in the preceding code.
3. Select the preceding test class in Eclipse and run it as TestNG test. You will see the
following test result in the Console window of Eclipse.
What just happened?
We have successfully created a test class that contains a test method that depends upon a
test group. The dependency is congured by providing the dependent group names to the
aribute dependsOnGroups, which uses the Test annotaon.
Like method dependency, group dependency also supports conguraon for a method to
depend on mulple groups. All dependent group names have to be provided as array names
to the aribute dependsOnGroups.
Depending on methods from different classes
As explained in the earlier examples, method dependency only works with other methods
that belong to the same class or in one of the inherited classes but not across dierent
classes. In case you need a test method that exists in a separate class; you can achieve this
by assigning the said test method to a group and conguring the dependent test method to
be dependent on the said group.
Let's create a sample test to learn how to create dependency across mulple classes.
Dependencies
[ 114 ]
Time for action – depending on a method from a different class
1. Create a new class named DifferentClassDependency under the test.
depends.groups package and replace the following code in it:
package test.depends.groups;
import org.testng.annotations.Test;
public class DifferentClassDependency {
@Test(dependsOnGroups={"test-group","same-class"})
public void testOne(){
System.out.println("Different class test method one");
}
@Test(groups={"same-class"})
public void testTwo(){
System.out.println("Different class test method two");
}
@Test(groups={"same-class"})
public void testThree(){
System.out.println("Different class test method three");
}
}
The preceding test class contains three test methods which print a message onto
the console when executed. Two of the test methods belong to group named same-
class whereas the third method, named testOne, depends on the groups named
test-group and same-class. The group test-group refers to the test that
belongs to the earlier created class named SimpleGroupTest.
2. Create a new le named diff-class-testng.xml under the current project
and replace the exisng code with the following code:
<suite name="Different class dependency Suite" verbose="1">
<test name="Different class dependency Test">
<packages>
<package name="test.depends.groups" />
</packages>
</test>
</suite>
The preceding testng XML contains a test that considers all the test class under
the package named test.depends.groups.
Chapter 5
[ 115 ]
3. Select the preceding testng XML in Eclipse and run it as TestNG suite.
You will see the following test result in the Console window of Eclipse.
What just happened?
We successfully created a test class that contains a test method which depends upon a
test method that belongs to another class. This is achieved using the dependsOnGroup
feature supported by TestNG. The previous results show that all the dependent methods
were executed prior to the execuon of the depending method.
Using regular expressions
Regular expressions feature as discussed in earlier chapters of this book is also supported
while using the dependsOnGroups feature in TestNG. This helps users to do name based
search on groups and add dependency onto the said groups for a test method.
In this secon we will create a sample program that does a regular expression search to
look for dependOnGroups.
Time for action – using regular expressions
1. Create a new package named regularexp under the exisng package test.
depends in the earlier project.
2. Create a new class named RegularExpressionTest under the test.depends.
regularexp package and replace the following code in it:
package test.depends.regularexp;
Dependencies
[ 116 ]
import org.testng.annotations.Test;
public class RegularExpressionTest {
@Test(dependsOnGroups={"starts-with.*"})
public void regularExpMethod(){
System.out.println("Dependent method");
}
@Test(groups={"starts-with-one"})
public void startsWithMethodOne(){
System.out.println("Starts with method one");
}
@Test(groups={"starts-with-two"})
public void startsWithMethodTwo(){
System.out.println("Starts with method two");
}
}
The preceding test class contains three test methods which print a message onto
the console when executed. Two of the test methods belong to dierent groups
named starts-with-one and starts-with-two, respecvely, whereas the
third method named regularExpMethod depends on all the groups whose
names start with the text starts-with.
3. Select the above test class in Eclipse and run it as TestNG test. You will see the
following test result in the Console window of Eclipse.
Chapter 5
[ 117 ]
What just happened?
We successfully created a test class which contains a test method that depends on groups
whose names start with the text starts-with. As you can see from the test results, all
the test methods that belonged to the parcular group got executed before the dependent
method. Regular expression-based search can be done on a text by using .* as discussed in
earlier chapters. Other than the preceding example of a search based on starts-with we
can easily do contains and ends-with search too.
Have a go hero
Create a sample program where a test method depends on all the groups whose name
contains a specic text in it.
XML-based dependency conguration
TestNG also allows group-based dependency to be dened inside the testng XML
conguraon le. This can be done when dening a test inside a suite. We write
some similar dependency programs that we have wrien earlier using XML conguraon.
Simple group dependency
In this secon we will write a simple XML conguraon le to dene a simple group
dependency for a test method.
Time for action – using simple dependency in XML
1. Create a new package named xml under the exisng package test.depends
in the earlier project.
2. Create a new class named SimpleXmlDependency under the test.depends.xml
package and replace the following code in it:
package test.depends.xml;
import org.testng.annotations.Test;
public class SimpleXmlDependency {
@Test(groups={"dependent-group"})
public void groupTestOne(){
System.out.println("Group Test method one");
}
Dependencies
[ 118 ]
@Test(groups={"test-group"})
public void groupTestTwo(){
System.out.println("Group test method two");
}
@Test(groups={"test-group"})
public void groupTestThree(){
System.out.println("Group Test method three");
}
}
The preceding test class contains three test methods which print a message onto
the console when executed. Two of the test methods belong to a dierent group
named test-group, whereas the third method named groupTestOne belongs
to group a named dependent-group.
3. Create a new XML named simple-xml-dependency.xml and add the following
code to it:
<suite name="Simple xml dependency Suite" verbose="1">
<test name="Simple xml dependency Test">
<groups>
<dependencies>
<group name="dependent-group" depends-on="test-group" />
</dependencies>
<run>
<include name="dependent-group" />
</run>
</groups>
<classes>
<class name="test.depends.xml.SimpleXmlDependency" />
</classes>
</test>
</suite>
The preceding testng XML conguraon le contains a single test inside the suite.
Group dependency is dened using the dependencies aribute under the groups
block. The group tag is used with the group name and the names of the group that
the said group depends on, as shown in the previous XML le.
Chapter 5
[ 119 ]
4. Select the previous XML le in Eclipse and run it as TestNG suite. You will see the
following test result in the Console window of Eclipse:
What just happened?
We successfully created a test class which contains a test method that depends on groups,
and the dependency conguraon was done using the testng XML le. As you can see
from the results, the test methods from the group test-group got executed before the
dependent test method.
Multigroup dependency
In this secon we will create a sample XML conguraon for dening a mulgroup
dependency for a parcular group.
Time for action – dening multigroup dependency in XML
1. Create a new class named MultiGrpXmlDependency under the test.depends.
xml package and replace the following code in it:
package test.depends.xml;
import org.testng.annotations.Test;
public class MultiGrpXmlDependency {
@Test(groups={"dependent-group"})
public void groupTestOne(){
System.out.println("Group Test method one");
}
Dependencies
[ 120 ]
@Test(groups={"test-group-one"})
public void groupTestTwo(){
System.out.println("Group test method two");
}
@Test(groups={"test-group-two"})
public void groupTestThree(){
System.out.println("Group Test method three");
}
}
The preceding test class contains three test methods which print a message onto
the console when executed. Each of the test methods belong to a dierent group.
2. Create a new XML with the name multigroup-xml-dependency.xml and add
the following code to it:
<suite name="Multi group xml dependency Suite" verbose="1">
<test name="Multi group xml dependency Test">
<groups>
<dependencies>
<group name="dependent-group" depends-on="test-group-one
test-group-two" />
</dependencies>
<run>
<include name="dependent-group" />
</run>
</groups>
<classes>
<class name="test.depends.xml.MultiGrpXmlDependency" />
</classes>
</test>
</suite>
The preceding testng XML conguraon contains a single test inside the suite.
Group dependency is dened using the dependencies aribute under the groups
block. The group tag is used with the group name and the names of the groups that
the said group depends on, as shown in the preceding XML le. In case the group is
dependent upon mulple groups, each group is separated by a space, as shown in
the preceding XML le.
Chapter 5
[ 121 ]
3. Select the preceding XML le in Eclipse and run it as TestNG suite. You will see the
following test result in the Console window of Eclipse:
What just happened?
We successfully created a test class which contains a test method that depends on mulple
groups, and where the dependency conguraon was done using the testng XML le. You
can see from the results that the test methods from the group test-group-one and
test-group-two got executed before the dependent test method which belongs to the
dependent-group. Mulple group dependency is dened in XML by providing all the
group names separated by a space.
Using regular expressions for dening dependency
In this secon we will create a sample XML conguraon le that denes a group
dependency using regular expressions.
Time for action – using regular expressions for dependency
1. Create a new class named RegularExpressionXmlTest under the test.
depends.xml package and replace the following code in it:
package test.depends.xml;
import org.testng.annotations.Test;
public class RegularExpressionXmlTest {
@Test(groups={"test"})
Dependencies
[ 122 ]
public void regularExpMethod(){
System.out.println("Dependent method");
}
@Test(groups={"starts-with-one"})
public void startsWithMethodOne(){
System.out.println("Starts with method one");
}
@Test(groups={"starts-with-two"})
public void startsWithMethodTwo(){
System.out.println("Starts with method two");
}
}
The preceding test class contains three test methods which print a message onto
the console when executed. Each of the test methods belongs to a dierent group.
2. Create a new XML le named regexp-xml-dependency.xml and add the
following code to it:
<suite name="Regexpxmldependency Suite" verbose="1">
<test name="Regexp xml dependency Test">
<groups>
<dependencies>
<group name="test" depends-on="starts-with.*" />
</dependencies>
<run>
<include name="test" />
</run>
</groups>
<classes>
<class name="test.depends.xml.RegularExpressionXmlTest" />
</classes>
</test>
</suite>
The preceding testng XML conguraon contains a single test inside the suite.
Group dependency is dened using the dependencies aribute under the
groups block. The group tag is used with the group name. Dependent group
is dened using the regular expressions.
Chapter 5
[ 123 ]
3. Select the preceding XML le in Eclipse and run it as TestNG suite. You will see the
following test result in the Console window of Eclipse:
What just happened?
We successfully created a test class which contains a test method for which the
dependency was congured using a regular expression. In the preceding sample program
dependent groups were added based on the names that start with starts with. For
regular expressions, search is done using the expression .*. This can also be used for ends
with and contains text-based search.
Pop quiz – dependencies
Q1. Which aribute has to be used with annotaon Test to dene a method dependency?
1. dependsOnMethods
2. dependsONMethod
3. methodsDependent
Q2. What kind of dependency can be congured using the testng XML conguraon le?
1. Methods
2. Groups
3. Both of the above
Dependencies
[ 124 ]
Summary
In this chapter we have learned about dependency feature in TestNG. We have learned
mulple ways to dene/congure test methods to be dependent on other test methods.
The dependency can be congured for both test methods and also for groups. We can
even congure/dene a dependency through the testng XML suite le. Use of regular
expressions is supported for groups and can be used for name-based search to add
groups to dependency.
In the next chapter we will cover the Factory annotaon provided by TestNG. We will
learn about its usage and how it's dierent from the DataProvider annotaon.
6
The Factory Annotation
In the previous chapter we learned about defining the dependency of tests on
other tests or a group of tests. In this section we will learn about the @Factory
annotation provided by TestNG. Factory allows tests to be created at runtime
depending on certain datasets or conditions.
In this chapter we'll cover the following topics:
What is factory
Passing parameters to test classes
The DataProvider annotaon with the @Factory annotaon
The DataProvider or @Factory annotaon
Dependency with the @Factory annotaon
What is factory?
Somemes we may need to run a set of tests with dierent data values. To achieve this
we may dene a separate set of tests inside a suite in the testng XML and test the
required scenario. The problem with this approach is that, if you get an extra set of data,
you will need to redene the test. TestNG solves this problem by providing the @Factory
annotaon feature. Factory in TestNG denes and creates tests dynamically at runme.
First factory program
Let's create a sample program using the @Factory annotaon of TestNG.
The Factory Annotaon
[ 126 ]
Time for action – rst factory test
Perform the following steps create your rst factory test:
1. Open Eclipse and create a Java project with the name FactoryProject with the
structure shown in the following screenshot. Please make sure that the TestNG library
is added to the build path of the project as menoned in Chapter 1, Geng Started.
2. Create a new class with name SimpleTest under the test.classes package
and replace the following code in it:
package test.classes;
import org.testng.annotations.Test;
public class SimpleTest {
@Test
public void simpleTest(){
System.out.println("Simple Test Method.");
}
}
The preceding test class contains only one test method, which prints a message
onto the console when executed.
3. Create another class with name SimpleTestFactory under the test.factory
package and replace the following code in it:
package test.factory;
import org.testng.annotations.Factory;
import test.classes.SimpleTest;
public class SimpleTestFactory {
@Factory
public Object[] factoryMethod(){
Chapter 6
[ 127 ]
return new Object[]{
new SimpleTest(),
new SimpleTest()
};
}
}
The preceding class denes a factory method inside it. A factory method is
dened by declaring @Factory above the respecve test method. It's mandatory
that a factory method should return an array of Object class (Object []) as
menoned in the preceding code snippet.
4. Select the previous factory test class in Eclipse and run it as a TestNG test. You will
see the following test result in the Console window of Eclipse:
What just happened?
We have successfully created a simple factory test class in the previous example. As you can
see in the preceding test results, the test method from the SimpleTestFactory class was
executed two mes. The execuon is based on the Object array returned by the factory
method. As the said method returns two objects of the SimpleTest class, TestNG looks
inside the specied returned object and executes all the test methods inside it. In this case,
as there was only one test method, TestNG executes the respecve test method.
Passing parameters to test classes
One of the main advantages of using the factory methods is that you can pass parameters
to test classes while inializing them. These parameters can then be used across all the test
methods present in the said classes. Let's write a small example, which passes parameters to
test classes.
The Factory Annotaon
[ 128 ]
Time for action – passing parameters to test classes
Perform the following steps for passing parameters to test classes:
1. Create new class with the name ParameterTest under the test.classes
package and replace the following code in it:
package test.classes;
import org.testng.annotations.Test;
public class ParameterTest {
private int param;
public ParameterTest(int param){
this.param = param;
}
@Test
public void testMethodOne(){
int opValue=param+1;
System.out.println("Test method one output: "+ opValue);
}
@Test
public void testMethodTwo(){
int opValue=param+2;
System.out.println("Test method two output: "+ opValue);
}
}
The constructor of the previous test class takes one argument as an integer,
which is assigned to a local variable param. This variable then is used in the two
test methods present in the test class. Each of the test methods adds a value to
param and prints it to the console on execuon.
2. Create another class with name ParameterFactory under the test.factory
package and replace the following code in it:
package test.factory;
import org.testng.annotations.Factory;
import test.classes.ParameterTest;
public class ParameterFactory {
@Factory
public Object[] paramFactory(){
return new Object[]{
Chapter 6
[ 129 ]
new ParameterTest(0),
new ParameterTest(1)
};
}
}
The preceding class denes a factory method inside it. This factory method
returns an array of the Object class containing two objects of ParameterTest
class. Select the previous factory test class in Eclipse and run it as a TestNG test.
You will see the following test result in the Console window of Eclipse:
What just happened?
We successfully created a factory method that passes a parameter to the test class
ParameterTest, which has been inialized with arguments 0 and 1 respecvely,
as shown in the previous code snippet. This parameter value is then used by the test
methods on execuon. As you can see from the preceding test results, each of the test
methods are executed two mes each. The parameters passed while inializing the test
class are used by the test methods and the console shows the respecve output.
Using DataProvider along with the @Factory annotation
The DataProvider feature can also be used with the @Factory annotaon for creang tests
at runme. This can be done by declaring the @Factory annotaon on a constructor of a
class or on a regular method.
Let's create an example, which uses the DataProvider annotaon along with the
@Factory annotaon.
The Factory Annotaon
[ 130 ]
Time for action – using DataProvider with Factory
Create a new class by the name DataProviderConsTest under the test.classes
package and replace the following code in it:
package test.classes;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DataProviderConsTest {
private int param;
@Factory(dataProvider="dataMethod")
public DataProviderConsTest(int param){
this.param=param;
}
@DataProvider
public static Object[][] dataMethod(){
return new Object[][]{
{0},
{1}
};
}
@Test
public void testMethodOne(){
int opValue=param+1;
System.out.println("Test method one output: "+ opValue);
}
@Test
public void testMethodTwo(){
int opValue=param+2;
System.out.println("Test method two output: "+ opValue);
}
}
The preceding class is similar to the test class, which we used earlier. The constructor of this
test class takes one argument as integer, which is assigned to a local variable param. This
variable then is used in the two test methods present in the test class. Each of the test methods
adds a value to param and prints it to the console on execuon. The constructor of the test
class is annotated with the @Factory annotaon. This annotaon uses a DataProvider method
named dataMethod for providing values to the constructor of the test class. The DataProvider
method returns a double object array in which the rst array represents the dataset, which
decides the number of mes the test will be iterated, whereas the second array is the actual
parameter value that will be passed to the test method per iteraon. The said double object
array contains two datasets with values 0 and 1. Select the previous test class in Eclipse and
run it as a TestNG test. You will see the following test result in the Console window of Eclipse:
Chapter 6
[ 131 ]
What just happened?
We have successfully created a test class that uses both, the @Factory annotaon along with
DataProvider to provide values to the factory method. The @Factory annotaon is applied to
the constructor of the test class. This inializes the test class mulple mes depending upon
the number of values provided by the DataProvider method. If there is an increase or decrease
in the datasets that are provided, it will reect test class inializaon accordingly.
DataProvider or Factory
Many people get confused when they read about the DataProvider and @Factory
annotaons – what to use when? and what is beer?
Let's take a look at both of their funconalies:
DataProvider: A test method that uses DataProvider will be executed a
mulple number of mes based on the data provided by the DataProvider.
The test method will be executed using the same instance of the test class
to which the test method belongs.
Factory: A factory will execute all the test methods present inside a test class
using a separate instance of the respecve class.
Let's create an example that shows the clear dierence between these two.
The Factory Annotaon
[ 132 ]
Time for action – the DataProvider test
1. Create a new class by the name DataProviderClass under the test.classes
package and replace the following code in it:
package test.classes;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProviderClass {
@BeforeClass
public void beforeClass(){
System.out.println("Before class executed");
}
@Test(dataProvider="dataMethod")
public void testMethod(String param){
System.out.println("The parameter value is: "+param);
}
@DataProvider
public Object[][] dataMethod(){
return new Object[][]{
{"one"},
{"two"}
};
}
}
The preceding class contains the testMethod and beforeClass methods.
testMethod takes a String argument and the value of the argument is provided by
the DataProvider method, dataMethod. The beforeClass method prints a message
onto the console when executed, and the same is the case with testMethod.
testMethod prints the argument passed onto it to the console when executed.
Chapter 6
[ 133 ]
2. Select the previous test class in Eclipse and run it as a TestNG test. You will see the
following test result in the Console window of Eclipse:
What just happened?
This example shows a test class that contains a test method, which uses a DataProvider
annotaon to provide data for its arguments. As you can see from the preceding test results
the class beforeClass is executed only one me irrespecve of how many mes the test
method is executed.
Time for action – the Factory test
1. Create a new class by the name ExampleTest under the test.classes package
and replace the following code in it:
package test.classes;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ExampleTest {
private String param="";
public ExampleTest(String param){
this.param=param;
}
@BeforeClass
public void beforeClass(){
System.out.println("Before class executed.");
}
The Factory Annotaon
[ 134 ]
@Test
public void testMethod(){
System.out.println("The the parameter value is: "+param);
}
}
The preceding class contains the testMethod and beforeClass methods. The
constructor of the test class takes a String argument value. Both beforeClass
and testMethod print a message onto console.
2. Create a new class with the name ExampleFactory under the test.factory
package and replace the following code in it:
package test.factory;
import org.testng.annotations.Factory;
import test.classes.ExampleTest;
public class ExampleFactory {
@Factory
public Object[] factoryMethod(){
return new Object[]{
new ExampleTest("one"),
new ExampleTest("two")
};
}
}
The preceding class contains a factory method that returns an Object array
of ExampleTest with dierent parameters.
3. Select the previous test class in Eclipse and run it as a TestNG test. You will
see the following test result in the Console window of Eclipse:
Chapter 6
[ 135 ]
What just happened?
This test class shows a factory class. As you can see from the previous test results, the
beforeClass method is executed before each execuon of testMethod. This shows that
factory implementaon executes the test method for each individual instance of the test
class. As we saw earlier DataProvider executes the test method (testMethod) for a single
instance of the test class.
Dependency with the @Factory annotation
We have seen dierent examples of factory implementaon in this chapter. In this secon
we will see how a dependency method is executed when used with the factory class.
Time for action – dependency with the @Factory annotation
1. Create a new class by the name DependencyTest under the test.classes
package and replace the following code in it:
package test.classes;
import org.testng.annotations.Test;
public class DependencyTest {
private int param;
public DependencyTest(int param){
this.param = param;
}
@Test(dependsOnMethods={"testMethodTwo"})
public void testMethodOne(){
System.out.println("Test method one with param values: "+
this.param);
}
@Test
public void testMethodTwo(){
System.out.println("Test method two with param values: "+
this.param);
}
}
This class contains two test methods testMethodOne and testMethodTwo, where
testMethodOne depends on testMethodTwo. The constructor of the class takes
one argument as integer, and sets its value to an internal variable named param.
Both of the test methods print their method name along with the param variable
value to console when executed.
The Factory Annotaon
[ 136 ]
2. Create another class under the test.factory package with the name
DependencyFactory and replace any exisng code with the following code:
package test.factory;
import org.testng.annotations.Factory;
import test.classes.DependencyTest;
public class DependencyFactory {
@Factory
public Object[] factoryMethod(){
return new Object[]{
new DependencyTest(1),
new DependencyTest(2)
};
}
}
3. Select the preceding factory class in Eclipse and run it as a TestNG test. You will see
the following test result in the Console window of Eclipse:
What just happened?
This example shows a test class that contains dependency test methods, where one test
method depends on another test method. As you can see from the previous test results both
the instances of testMethodTwo were executed before any instance of testMethodOne.
This is the default behavior of a factory implementaon in TestNG, it will execute all the
instances of the dependent test methods before the actual test method. Unfortunately,
this behavior may not fulll our tesng needs somemes. To execute the test methods in
sequenal order for each instance we need to use a testng XML conguraon le.
Chapter 6
[ 137 ]
Let's create a testng XML conguraon to execute the previous test in sequenal order
based on the instance.
Time for action – running a dependency test sequentially
Perform the following test to run a dependency test sequenally:
1. Create a new le with the name factory-testng.xml under the exisng project:
<suite name="Factory suite" verbose="1" >
<test name="Factory test" group-by-instances="true">
<classes>
<class name="test.factory.DependencyFactory" />
</classes>
</test>
</suite>
This XML conguraon contains only a test inside it. This test executes the
DependencyFatory class. To run the dependent methods according to the
sequence, they are supposed to run a conguraon aribute group-by-
instance, which is set to true.
2. Select the preceding testng XML in Eclipse and run it as a TestNG suite.
You will see the following test result in the Console window of Eclipse:
What just happened?
This example shows how to run dependent methods run for each sequence rather
than running the dependent methods with all rst and then the rest methods. The
aribute group-by-instances is currently used along with the test tag but can
also be used with the suite tag.
The Factory Annotaon
[ 138 ]
Have a go hero
Having gone through the chapter, feel free to aempt the following:
Create a factory test with DataProvider test that has a depend-on-method congured
Create a factory method that denes tests from mulple test classes
Pop quiz – the Factory annotation
Q1. Factory annotaon can be applied at class level.
1. True
2. False
Q2. Which of the following aributes has to be used to order the execuon tests by instance
in a factory class?
1. order-by-instances
2. group-by-instances
3. execute-by-instances
Summary
In this chapter we have learned about the Factory feature provided by TestNG. Factory allows
users to create tests at runme. We can create n number of tests at runme depending upon
some data sets. We have learned the dierences between DataProvider and the @Factory
annotaon and how each of them executes the tests. We also learned on how to use
DataProvider along with the factory implementaon for dening tests at runme.
In the next chapter we will cover the parallelism feature of TestNG, which allows users to
congure their tests to be run in a parallel/multhreaded environment.
7
Parallelism
In the previous chapter we had learned about the @Factory annotation,
its advantages, its comparison with data-driven tests, and how it can be
used along with data-driven tests. In this chapter we will cover the parallelism
or the multithreading feature provided by TestNG. We will also learn about
the different configuration options provided by TestNG for running the tests
in parallel or multithreaded mode.
In this chapter we'll cover the following topics:
Parallelism
A simple multhreaded test
Running test methods in parallel
Running test classes in parallel
Running tests in a suite in parallel
Conguring an independent test method to run in parallel
Advantages and uses
Parallelism
[ 140 ]
Parallelism
Parallelism or multhreading in soware terms is dened as the ability of the soware,
operang system, or program to execute mulple parts or subcomponents of another
program simultaneously. This ability is provided by TestNG too, it allows the tests to run
in parallel or multhreaded mode. This means that based on the test suite conguraon,
dierent threads are started simultaneously and the test methods are executed in them.
This gives a user a lot of advantages over normal execuon, mainly reducon in execuon
me and ability to verify a multhreaded code. There are dierent ways in which this feature
can be congured in TestNG. We will learn about these conguraons going forward in this
chapter. Let's start with a sample program rst.
A simple multithreaded test
Let's write our rst multhreaded program and see how it works.
Time for action – writing rst parallel test
Carry out the following steps to write the rst parallel test:
1. Open Eclipse and create a Java project with the name Parallelism with the
structure shown in the following screenshot. Please make sure that the TestNG
library is added to the build path of the project as menoned in Chapter 1,
Geng Started.
2. Create a new class with the name SimpleClass under the test.parallelism
package and replace the following code in it:
package test.parallelism;
import org.testng.annotations.Test;
public class SimpleClass {
@Test
public void testMethodsOne() {
long id = Thread.currentThread().getId();
System.out.println("Simple test-method One. Thread id is:
"+id);
}
@Test
Chapter 7
[ 141 ]
public void testMethodsTwo() {
long id = Thread.currentThread().getId();
System.out.println("Simple test-method Two. Thread id is:
"+id);
}
}
The preceding test class contains two test methods, which prints a message onto
the console when executed. The ID of the thread on which the current method is
being executed is evaluated using the Thread.currentThread.getId() code.
3. Create a new le named simple-test-testng.xml under the project and
replace the following code in it:
<suite name="Simple Suite" parallel="methods" thread-count="2" >
<test name="Simple test">
<classes>
<class name="test.parallelism.SimpleClass" />
</classes>
</test>
</suite>
The preceding XML denes a simple test suite which contains only a single
test inside it. The test considers the class SimpleClass for test execuon.
Multhreading or parallelism is congured using the aribute parallel
and thread-count at the suite level as shown in the previous XML le.
The parallel be done for each class, each method, or for each test in the
suite. The thread-count aribute is used to congure the maximum number
of threads to be spawned for each suite.
4. Select the previous testng XML le in Eclipse and run it as a TestNG suite.
You will see the following test result in the Console window of Eclipse:
Parallelism
[ 142 ]
What just happened?
We have successfully created a test class, which is executed in multhreaded or parallel
mode. The testng XML congures TestNG to execute the said test in multhreaded mode
for each method. This is done by using the aributes parallel and thread-count at
suite level while dening the testng XML. The values of these aributes are methods
and 2 respecvely. The rst value congures TestNG for execung each test method in a
separate thread whereas the laer congures it to spawn 2 threads for the said execuon.
The previous test result clearly shows that each test method is executed in a dierent thread.
This is idened by the ID of the thread that is printed on the console.
Running test methods in parallel
In our previous example we had seen a simple class having two test methods being executed
in mulple threads. As menoned previously, TestNG provides mulple ways to execute the
tests in a multhreaded condion, one of them is execung each test method in a single
thread. This mode reduces the execuon me signicantly because more tests are executed
in parallel, hence reducing the total execuon me. In this secon we will learn about
execung test methods in parallel and will write a sample program, which executes
mulple test methods from dierent classes in parallel.
Time for action – running test methods in parallel
Perform the following steps to create test methods in parallel:
1. Create new class with the name SampleTestMethod under the test.
parallelism package and replace the following code in it:
package test.parallelism;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class SampleTestMethod {
@BeforeMethod
public void beforeMethod(){
long id = Thread.currentThread().getId();
System.out.println("Before test-method. Thread id is: "+id);
}
@Test
public void testMethodsOne() {
long id = Thread.currentThread().getId();
Chapter 7
[ 143 ]
System.out.println("Simple test-method One. Thread id is:
"+id);
}
@Test
public void testMethodsTwo() {
long id = Thread.currentThread().getId();
System.out.println("Simple test-method Two. Thread id is:
"+id);
}
@AfterMethod
public void afterMethod(){
long id = Thread.currentThread().getId();
System.out.println("After test-method. Thread id is: "+id);
}
}
The preceding test class contains two test methods, which prints a message onto
the console when executed. The ID of the thread on which the current method is
being executed is evaluated using the Thread.currentThread.getId() code.
It also contains the before and aer methods, which also prints the thread ID of
the current thread onto the console when executed.
2. Create a new le named methods-test-testng.xml under the project and
replace the following code in it:
<suite name="Test-method Suite" parallel="methods" thread-
count="2" >
<test name="Test-method test" group-by-instances="true">
<classes>
<class name="test.parallelism.SampleTestMethod" />
</classes>
</test>
</suite>
The preceding XML denes a simple test suite, which contains only a single test
inside it. The test considers the class SampleTestMethod for test execuon.
Parallelism
[ 144 ]
3. Select the previous testng XML le in Eclipse and run it as a TestNG suite.
You will see the following test result in the Console window of Eclipse:
Note that the Id value shown in the previous screenshot may not be
the same in your console output. The Id value is assigned at runme
by the Java virtual machine (JVM) during execuon.
What just happened?
We have successfully created a test class, which is executed in multhreaded or parallel
mode. Here, for execung the tests in parallel we have congured TestNG to run test
methods in parallel by providing the value methods to the parallel aribute of suite.
Also the test is congured to spawn two threads for the said test suite; this is done by
providing the value 2 to the thread-count aribute at the suite level.
The previous test result clearly shows that each test method and its respecve before and
aer method is executed in a dierent thread. This is idened by the ID of the thread that
is printed on the console.
Running test classes in parallel
In our earlier example we had wrien a sample program that shows how to congure and
run test methods in parallel in TestNG. In this secon we will learn about execung test
classes in parallel; each test class that is part of the test execuon will be executed in its
own thread. Let's write a sample program, which executes mulple test classes in parallel.
Chapter 7
[ 145 ]
Time for action – running test classes in parallel
Perform the following steps to create test classes in parallel:
1. Create new class with the name SampleTestClassOne under the test.
parallelism package and replace the following code in it:
package test.parallelism;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SampleTestClassOne {
@BeforeClass
public void beforeClass(){
long id = Thread.currentThread().getId();
System.out.println("Before test-class. Thread id is: "+id);
}
@Test
public void testMethodOne() {
long id = Thread.currentThread().getId();
System.out.println("Sample test-method One. Thread id is:
"+id);
}
@Test
public void testMethodTwo() {
long id = Thread.currentThread().getId();
System.out.println("Sample test-method Two. Thread id is:
"+id);
}
@AfterClass
public void afterClass(){
long id = Thread.currentThread().getId();
System.out.println("After test-class. Thread id is: "+id);
}
}
The preceding test class contains two test methods, which prints a message onto
the console when executed. The ID of the thread on which the current method
is being executed is evaluated using the Thread.currentThread.getId() code.
It also contains the before and aer class methods, which also print the thread ID
of the current thread onto the console when executed at start and end of the
class execuon.
Parallelism
[ 146 ]
2. Create a new class with the name SampleTestClassTwo under the
test.parallelism package and replace the following code in it:
package test.parallelism;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SampleTestClassTwo {
@BeforeClass
public void beforeClass(){
long id = Thread.currentThread().getId();
System.out.println("Before test-class. Thread id is: "+id);
}
@Test
public void testMethodOne() {
long id = Thread.currentThread().getId();
System.out.println("Sample test-method One. Thread id is:
"+id);
}
@Test
public void testMethodTwo() {
long id = Thread.currentThread().getId();
System.out.println("Sample test-method Two. Thread id is:
"+id);
}
@AfterClass
public void afterClass(){
long id = Thread.currentThread().getId();
System.out.println("After test-class. Thread id is: "+id);
}
}
The preceding test class also contains two test methods, which print a message
onto the console when executed. The ID of the thread on which the current
method is being executed is evaluated using the Thread.currentThread.
getId() code. It also contains the before and aer class methods which also
print the thread ID of the current thread onto the console when executed at
start and end of the class execuon.
Chapter 7
[ 147 ]
3. Create a new le named classes-test-testng.xml under the project and
replace the following code in it:
<suite name="Test-class Suite" parallel="classes" thread-count="2" >
<test name="Test-class test" >
<classes>
<class name="test.parallelism.SampleTestClassOne" />
<class name="test.parallelism.SampleTestClassTwo" />
</classes>
</test>
</suite>
The preceding XML denes a simple test suite, which contains two classes in it:
SampleTestClassOne and SampleTestClassTwo.
4. Select the previous testng XML le in Eclipse and run it as a TestNG suite.
You will see the following test result in the Console window of Eclipse:
Note that the Id value in the preceding output may not be the same
in your console output. The Id value is assigned at runme by the Java
virtual machine (JVM) during execuon.
Parallelism
[ 148 ]
What just happened?
We have successfully created a test suite, which is executed in multhreaded or parallel
mode. Here for execung each class in parallel we have congured TestNG by providing the
value classes to the parallel aribute of suite. Also the test is congured to spawn two
threads for the said test suite; this is done by providing the value 2 to the thread-count at
the suite level.
The previous test result clearly shows that each test class and its respecve beforeClass
and afterClass methods are executed in a dierent thread. This is idened by the ID
of the thread that is printed on the console.
Running tests inside a suite in parallel
In our previous example we had wrien a sample program that demonstrates how to
congure and run test classes in parallel in TestNG. In this secon we will learn about
execung each test inside a suite in parallel, that is, each test that is part of the test
suite execuon will be executed in its own separate respecve thread. Let's write a
sample program, which executes mulple tests present in a suite in parallel.
Time for action – running tests inside a suite in parallel
Perform the following steps for running tests inside a suite in parallel:
1. Create a new class with the name SampleTestSuite under the test.
parallelism package and replace the following code in it:
package test.parallelism;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class SampleTestSuite {
String testName="";
@BeforeTest
@Parameters({ "test-name" })
public void beforeTest(String testName){
this.testName=testName;
long id = Thread.currentThread().getId();
System.out.println("Before test "+testName+". Thread id is:
Chapter 7
[ 149 ]
"+id);
}
@BeforeClass
public void beforeClass(){
long id = Thread.currentThread().getId();
System.out.println("Before test-class "+testName+". Thread id
is: "+id);
}
@Test
public void testMethodOne() {
long id = Thread.currentThread().getId();
System.out.println("Sample test-method "+testName+". Thread id
is: "+id);
}
@AfterClass
public void afterClass(){
long id = Thread.currentThread().getId();
System.out.println("After test-method "+testName+". Thread id
is: "+id);
}
@AfterTest
public void afterTest(){
long id = Thread.currentThread().getId();
System.out.println("After test "+testName+". Thread id is:
"+id);
}
}
The preceding test class contains a test method, which prints a message onto
the console when executed. The ID of the thread on which the current method
is being executed is printed along with the said message. The class also contains
the beforeTest/afterTest and beforeClass/afterClass methods. The
beforeTest method takes a parameter, which passed through the testng XML le.
2. Create a new le named test-testng.xml under the project and replace the
following code in it:
<suite name="Parallel tests" parallel="tests" thread-count="2" >
<test name="Test One">
<parameter name="test-name" value="Test One"/>
<classes>
<class name="test.parallelism.SampleTestSuite" />
</classes>
Parallelism
[ 150 ]
</test>
<test name="Test Two">
<parameter name="test-name" value="Test Two"/>
<classes>
<class name="test.parallelism.SampleTestSuite" />
</classes>
</test>
</suite>
The preceding XML contains two tests in it, each including the SampleTestSuite
class for test execuon. Each test passes the parameter value Test One and Test
Two to test-name. This is passed to the beforeTest method, which sets the value
of testName in the test class. This value is then used by the test methods to idenfy
the test that is being executed.
3. Select the previous testng XML le in Eclipse and run it as a TestNG suite. You will
see the following test result in the Console window of Eclipse:
What just happened?
We have successfully created a test suite, which is executed in multhreaded or parallel
mode. Multhreading or parallelism is congured to execute each test in a separate thread.
Here, for execung each test in parallel we have congured TestNG by providing the value
tests to the parallel aribute of suite. Also the test is congured to spawn two threads
for the said test suite; this is done by providing the value 2 to the thread-count aribute
at the suite level.
Chapter 7
[ 151 ]
The previous test result clearly shows that each test in a suite is executed in its respecve
thread. This is idened by the ID of the thread that is printed on the console.
Conguring an independent test method to run in
multiple threads
Earlier we discussed how to run classes, methods, and tests in parallel or in multhreaded
mode. TestNG also provides the exibility to congure a test method to be run in a
multhreaded environment. This is achieved by conguring it while using the Test
annotaon on a method.
Let's look at an example of how to congure a test method to run in a multhreaded
environment.
Time for action – running independent test in threads
Perform the following steps to run independent tests in threads:
1. Create new class with the name IndependentTestThreading under the test.
parallelism package and replace the following code in it:
package test.parallelism;
import org.testng.annotations.Test;
public class IndependentTestThreading {
@Test(threadPoolSize=3,invocationCount=6,timeOut=1000)
public void testMethod(){
Long id = Thread.currentThread().getId();
System.out.println("Test method executing on thread with id:
"+id);
}
}
The preceding test class contains a test method, which prints a message onto the
console when executed. The ID of the thread on which the current method is being
executed is printed along with the said message. The method is congured to run in
multhreaded mode by using the threadPoolSize aribute along with the Test
annotaon. The value of the threadPoolSize is set to 3 in the previous class;
this congures the test method to be run in three dierent threads. The other two
aributes, invocationCount and timeOut, congures the test to be invoked a
mulple number of mes and fail if the execuon takes more me. The value of these
two aributes is set to 6 and 1000 respecvely, conguring the test method to be run
six mes and fail if the execuon takes more than 1000 milliseconds.
Parallelism
[ 152 ]
2. Create a new le named independent-test-testng.xml under the project
and replace the following code in it:
<suite name="Independent test Suite" >
<test name="Independent test">
<classes>
<class name="test.parallelism.IndependentTestThreading" />
</classes>
</test>
</suite>
The preceding code denes a single test, which includes the
IndependentTestThreading class for the test execuon. The
test is not congured with any multhreading or parallel execuon.
3. Select the previous testng XML le in Eclipse and run it as TestNG suite.
You will see the following test result in the Console window of Eclipse:
What just happened?
We have successfully created a test class, which contains a test method that is congured
to run in multhreaded or parallel mode. The test method is executed mulple mes based
on the invocationCount aribute value. Each execuon is done in a separate thread that
is clearly visible from the test report output. This feature is useful when you want to run only
a xed number of test methods in multhreaded mode and not the whole test suite.
Chapter 7
[ 153 ]
Have a go hero
Create a class that contains the BeforeClass and AfterClass annotated methods
along with a test method. Run the said class in parallel by conguring it to run each
method in parallel. Verify in which thread the BeforeClass/AfterClass annotated
methods are executed.
Advantages and uses
Parallelism or multhreaded execuon can provide a lot of advantages to the users.
The following are two:
Reduces execuon me: As tests are executed in parallel, mulple tests get
executed simultaneously, hence reducing the overall me taken to execute the tests
Allows multhreaded tests: Using this feature, we can write tests to verify certain
multhreaded code in the applicaons
This feature is vastly used by the QA industry for funconal automaon tesng. This feature
helps QA guys congure their tests to be executed easily in mulple browsers or operang
systems simultaneously.
Pop quiz – parallelism
Q1. What is the aribute that needs to be used to congure TestNG tests to run in parallel?
1. threading
2. thread-count
3. parallel
Q2. Which of the following values have to be menoned in the XML conguraon le to
run test methods in parallel?
1. test-methods
2. method
3. methods
Parallelism
[ 154 ]
Summary
In this chapter we learned about the parallel or multhreading feature of TestNG.
We have looked into dierent ways a test suite can be congured to run tests in parallel.
This feature has a wide range of uses when combined with other features such as
parameterizaon and grouping of tests. These can be used in dierent ways depending
upon dierent requirements and scenarios.
In the next chapter we will learn about build automaon tools and how to use them to build
and run TestNG tests. We will learn about the advantages of using build tools and how the
use of such tools can help us with tesng.
8
Using Build Tools
In the previous chapter we had covered the parallelism feature provided by
TestNG which helps users to run the tests in parallel. In this chapter we will
learn about the build automation tools available, their advantages, and
how to use them to automate our TestNG tests.
In this chapter we'll cover the following topics:
Build automaon
Dierent build automaon tools available
Ant and using Ant with TestNG
Maven and using Maven with TestNG
Build automation
Build automaon can be dened as the process of scripng and automang the compiling,
running, deploying, and packaging of a source code. This is applicable for every kind of
soware language irrespecve of the type. There are certain common tasks that every
build tool supports as part of the build automaon such as cleanup, compiling, execung,
reporng, and publishing.
Every tool has a dierent way of achieving the said tasks. For some tools certain tasks are
predened but for other tools ulies are provided and user can use them to manually
congure them.
Using Build Tools
[ 156 ]
Advantages of build automation
Following are the advantages of automang a build:
Eliminates manual eort in building and deploying process
Eliminates the redundant tasks
Can be used to keep history of the builds made
Saves me
Improves product quality
Build automaon tools when used with connuous integraon tools such
as Hudson, helps in schedule triggering the builds at regular intervals
Different build tools available
For each kind of soware language in the industry there are a variety of build tools
that can be used for build automaon. When it comes to Java or Java related languages,
following are the major build tools that are being used by the soware industry:
Ant
Maven
Gradle
As part of this chapter we will cover Ant and Maven for automang our builds to compile
and run our TestNG tests.
Ant
Ant is one of the most commonly used build tools by the soware industry for the build
automaon of Java-based products. It is congured using an XML le and by default the
conguraon le name for Ant is named as build.xml. In this secon we will learn how
to install the Ant tool and use it to run TestNG tests.
Installing Ant
Follow the given steps to install Ant onto your system:
1. Download Ant from the Apache site:
http://ant.apache.org/bindownload.cgi.
2. Download Java JDK and set JAVA_HOME as an environment variable poinng to
your JDK installaon directory.
3. Also add ANT_HOME poinng to the downloaded ant directory as an
environment variable.
Chapter 8
[ 157 ]
4. Add the path to the bin directory which exists under the ant directory to
your system path (path variable).
5. Open a terminal window and type the command ant and press Enter. You will
see a message as shown in the following screenshot:
Using Ant
Before we go ahead and start using Ant, there are certain terminologies that we should
be familiar with before we actually use Ant for running our TestNG tests:
Project: Project is the starng point of the Ant conguraon le and consists of
the enre conguraon with respect to building a project.
Tasks: These are mainly called Ant tasks. These are the dierent funconalies
that Ant provides. A task in Ant can be idened by the XML tag used. Some of
the common tasks are mkdir, delete, target, path, and so on.
Target: An Ant target is nothing but enclosing a set of steps or task into dened
secon. Targets act as commands while using the Ant build.
Any in-detail informaon about Ant is out of scope of this book but, you can nd the same
informaon on its website, http://ant.apache.org/manual/.
Now let's create a sample project and write an Ant conguraon le to build and run the
respecve sample project.
Time for action – using Ant to run TestNG tests
1. Open Eclipse and create a new Java project named BuildToolProject with
following structure:
Using Build Tools
[ 158 ]
2. Create a new class le named SampleBuildTest under the test package
and replace the exisng code with the following code:
package test;
import org.testng.annotations.Test;
public class SampleBuildTest {
@Test
public void testMethodOne(){
System.out.println("Test method one executed");
}
@Test
public void testMethodTwo(){
System.out.println("Test method two executed");
}
}
The above class contains two test methods which print a message onto the
console when executed.
3. Download the TestNG JAR as menoned in the Chapter 1, Geng Started, and copy
the said JAR onto the lib folder under the Java project.
4. Create a new le named testng.xml under the said project and paste the
following code onto it:
<suite name="Sample Build Suite">
<test name="Sample Build test">
<classes>
<class name="test.SampleBuildTest" />
</classes>
</test>
</suite>
The preceding XML denes a simple test suite with a single test. The test considers
the test class SampleBuildTest as part of the test.
5. Create a new le named build.xml under the project and add the following
code to it:
<project name="Testng Ant build" basedir=".">
<!-- Sets the property variables to point to respective
directories -->
<property name="report-dir" value="${basedir}/html-report" />
<property name="testng-report-dir" value="${report-dir}/TestNG-
report" />
<property name="lib-dir" value="${basedir}/lib" />
Chapter 8
[ 159 ]
<property name="bin-dir" value="${basedir}/bin-dir" />
<property name="src-dir" value="${basedir}/src" />
<!-- Sets the classpath including the bin directory and all the
jars underthe lib folder -->
<path id="test.classpath">
<pathelement location="${bin-dir}" />
<fileset dir="${lib-dir}">
<include name="*.jar" />
</fileset>
</path>
<!-- Deletes and recreate the bin and report directory -->
<target name="init">
<delete dir="${bin-dir}" />
<mkdir dir="${bin-dir}" />
<delete dir="${report-dir}" />
<mkdir dir="${report-dir}" />
</target>
<!-- Compiles the source code present under the "src-dir" and
place classfiles under bin-dir -->
<target name="compile" depends="init">
<javac srcdir="${src-dir}" classpathref="test.classpath"
includeAntRuntime="No" destdir="${bin-dir}" />
</target>
<!-- Defines a TestNG task with name "testng" -->
<taskdef name="testng" classname="org.testng.TestNGAntTask"
classpathref="test.classpath" />
<!-- Executes the testng tests configured in the testng.xml file
-->
<target name="testng-execution" depends="compile">
<mkdir dir="${testng-report-dir}" />
<testng outputdir="${testng-report-dir}" classpathref="test.
classpath" useDefaultListeners="true">
<!-- Configures the testng xml file to use as test-suite -->
<xmlfileset dir="${basedir}" includes="testng.xml" />
</testng>
</target>
</project>
Using Build Tools
[ 160 ]
The preceding XML denes an Ant build XML le. The le denes dierent steps in
the build process as Ant targets:
init: Cleans the compiled code and report directory
compile: Compiles the java source code and puts it under the bin directory
testng-execution: Uses the defined testng xml file for TestNG test
execution and generates the test report for it
6. Open command prompt and go to the respecve Java project path in the system.
You can nd the system path of a parcular project by selecng the said project,
then right-click and go to the Properes | Resources secon. Under the Resource
secon you will nd a property named Locaon which shows the project folder path.
7. Under the respecve Java project folder type the command ant testng-
execution and press Enter.
8. Ant will compile and execute your TestNG tests. You will see the following screen:
What just happened?
We have successfully created an Ant script le for compiling, building, and running our
TestNG tests. Ant target gets executed in the following sequence:
init
compile
testng-execution
Chapter 8
[ 161 ]
You can see in the previous screenshot of Ant execuon where the dierent targets were
executed and the Ant tasks that were executed as part of each Ant target. We can dene and
execute as many Ant targets as we want depending upon our project build requirements.
Dierent teams have dierent requirements for build automaon. There are a lot of
advantages and disadvantages of Ant. Certain advantages include ability to manually
dene the steps that need to be executed as part of the build and easy integraon with
connuous integraon systems.
Different congurations to be used with TestNG task
TestNG allows dierent conguraon opons to be used along with the testng task when
using it inside the build XML le of the Ant. The following are a few conguraons that can
be used along with the testng task:
groups: The list of the groups to run separated by comma or spaces
excludedgroups: The list of groups to be excluded from the test execuon
listeners: A list of comma separated by class names that implements the
TestNG ITestListener or IReporter and needs to be added as listener
outputdir: The output directory for generaon of the report
parallel: The parallel mode to use either methods, classes, or tests
threadCount: The number of threads that can be used for the said run
testname: Sets the default testname for the test
timeOut: The maximum me in milliseconds within which individual tests
should get executed
The above conguraons can be used as aributes to the said Ant task. Following is a simple
example code which will use the groups and parallel opon with the testng task while
execung the TestNG tests in Ant:
<testng outputdir="${testng-report-dir}" groups="test-group"
parallel="methods" classpathref="test.classpath"
useDefaultListeners="true" />
Have a go hero
Having gone through the chapter, feel free to aempt the following:
Write an Ant le that generates the report in a dierent directory other than the
default test output
Write an Ant le to build and run tests that belong to a parcular group without
using the TestNG XML conguraon le
Using Build Tools
[ 162 ]
Maven
Maven is another build tool that is commonly used by the industry as a build automaon
tool. Maven also uses XML for build conguraon and for dening build steps. The
advantages of using maven is that it itself maintains the dependent libraries of our project
once congured. The user can congure the dependent libraries on which the respecve
project code depends upon and maven will download those JARs/libs and their dependent
JARs (if any) during the build process.
Also Maven predenes some basic directory structure for project source code and test code.
These directories will by default be considered during the build process if not
explicitly congured.
Installing Maven
Installing Maven is similar to Ant. The following are the steps to install Maven:
1. Download Maven from the Apache site, http://maven.apache.org/download.
cgi.
2. Download Java JDK and set JAVA_HOME as an environment variable poinng to your
JDK installaon directory.
3. Also add MAVEN_HOME poinng to the downloaded maven directory as an
environment variable.
4. Add the path to the bin directory which exists under the maven directory to your
system path (Path variable).
5. Open a terminal window and type the command mvn and press Enter. You will see a
message as shown in the following screenshot:
Chapter 8
[ 163 ]
Using Maven
Before we go ahead with using Maven we should get familiar with some of the basic features
and terminologies that we will be using in our tests:
Project: As in the case with Ant, in Maven this is also dened as the start of the
conguraon and contains the respecve dependency and conguraon related
to a project.
Plugins: They are ulies provided as part of Maven, for achieving the dierent
kinds of steps involved in the build process.
Dependencies: They are used to congure the project dependency. The user
can congure the API, JARS, and version on which the respecve project is
dependent upon.
Any detailed discussions about Maven are out of scope of this book , however, you can
nd more info about it on its website http://maven.apache.org/.
Now that we have installed Maven onto the system, let's now go ahead and use Maven
to run our TestNG tests.
Time for action – using Maven to run TestNG tests
1. Create a new le named pom.xml under the project and add the following code
to it:
<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
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test.maven</groupId>
<artifactId>sample-maven-build</artifactId>
<version>1</version>
<name>sample-maven-build</name>
<build>
<!-- Source directory configuration -->
<sourceDirectory>src</sourceDirectory>
<plugins>
<!-- Following plugin executes the testng tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
<configuration>
Using Build Tools
[ 164 ]
<!-- Suite testng xml file to consider for test execution -->
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<!-- Compiler plugin configures the java version to be used
for compiling the code -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Dependency libraries to include for compilation -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.3.1</version>
</dependency>
</dependencies>
</project>
The preceding XML denes a Maven pom.xml le. The le denes dierent
conguraons for maven to build the project. The funconality of each
secon is already menoned as inline comments in the code.
2. Open the command prompt and go to the respecve Java project path
in the system.
3. Under the respecve Java project folder type the command mvn test
and press Enter.
Chapter 8
[ 165 ]
4. Maven downloads the respecve dependencies and will compile and execute
your TestNG tests. You will see the following output in the command prompt:
What just happened?
We have successfully created a Maven script for compiling and running the TestNG tests
through Maven. Maven has a predened step of compiling the code before execung
the tests when we try to run our tests. The previous screenshot shows the dierent steps
involved in compiling and running the tests by Maven build. Maven can be used with any
of the connuous integraon systems. The plugin maven-surefire-plugin is used to
congure and execute the tests. Here the said plugin is used to congure the testng.xml
for the TestNG test and generate test reports. The plugin maven-compiler-plugini used
to help in compiling the code and using the parcular JDK version for compilaon.
Using Build Tools
[ 166 ]
Different congurations to be used with Maven
Maven also has similar conguraons to Ant that can be used. Following are few of the
conguraons that can be used with the Surere plugin when using Maven as a build tool:
groups: The list of the groups to run separated by commas or spaces
excludedgroups: The list of groups to be excluded from the test execuon
listeners: A list of comma separated by class names that implements the TestNG
ITestListener or IReporter and needs to be added as listener
outputdir: The output directory for generaon of the report
parallel: The parallel mode to use either methods, classes, or tests
threadCount: Number of threads that can be used for the run
testname: Sets the default test name for the test
timeOut: The maximum me in milliseconds within which the individual tests
should get executed
The above conguraons can be used as XML tags for conguraon while using the Surere
plugin to the said Ant task. Following is a simple example code to use the threadCount and
parallel opon with the testng task:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
<configuration>
<!-- Suite testng xml file to consider for test execution -->
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
<parallel>tests</parallel>
<threadCount>5</threadCount>
</configuration>
</plugin>
Have a go hero
Having gone through the chapter, feel free to aempt the following:
Write a Maven le that generates the report in a dierent directory other than the
default test output
Write an Maven le to build and run tests that belong to parcular group without
using the TestNG XML conguraon le
Chapter 8
[ 167 ]
Pop quiz – build tools
Q1. Ant has an inbuilt task to run TestNG tests. Is this statement correct?
1. Yes
2. No
Q2. Which of the following conguraon opons can be used with the Ant testng
task groups?
1. excludedgroups
2. outputdir
3. All of the above
4. None of the Above
Q3. Which of the following plugins are used to congure and execute TestNG tests in Maven?
1. maven-surefire-plugin
2. maven-testng-plugin
3. maven-compiler-plugin
Summary
In this chapter we learned about the build automaon tools and advantages of using them.
We also learned about the Ant and Maven build tools which are the major build automaon
tools used in the industry. We covered how to install and use Ant and Maven as build
automaon tools for running TestNG tests.
As covered in this chapter, build automaon tools have a lot of advantages and its always
good if we integrate our TestNG tools with any of the build Automaon tools. This gives a
lot of exibility to our tesng framework. This also allows the tests to be easily integrated
with the development code and helps in execung our tests as part of the applicaon build
process, and idenes any failure in the build stage itself.
In the next chapter we will cover the logging and reporng feature provided by TestNG
which helps users to add custom loggers or reporters to TestNG.
9
Logging and Reports
In the previous chapter we covered the uses of build tools which help our
TestNG tests in a lot of different ways. In this chapter we will learn about
writing extensions in TestNG for logging and generating custom reports from
them. We will also learn about different report formats available and how to
generate some nice open source reports.
In this chapter we'll cover the following topics:
Logging and reporng
Wring your own logger
Wring your own reporter
TestNG HTML and XML reports
Generang a JUnit HTML report
Generang a ReportNG report
Generang a Reporty-ng (former TestNG-xslt) report
Logging and reporting
Reporng is the most important part of any test execuon, reason being it helps the user
to understand the result of the test execuon, point of failure, and reasons for the failure.
Logging, on the other hand, is important to keep an eye on the execuon ow or for
debugging in case of any failures.
Logging and Reports
[ 170 ]
TestNG by default generates a dierent type of report for its test execuon. This includes an
HTML and an XML report output. TestNG also allows its users to write their own reporter and
use it with TestNG. There is also an opon to write your own loggers, which are noed at
runme by TestNG.
There are two main ways to generate a report with TestNG:
Listeners: For implemenng a listener class, the class has to implement the org.
testng.ITestListener interface. These classes are noed at runme by
TestNG when the test starts, nishes, fails, skips, or passes.
Reporters: For implemenng a reporng class, the class has to implement an org.
testng.IReporter interface. These classes are called when the whole suite run
ends. The object containing the informaon of the whole test run is passed to this
class when called.
Each of them should be used depending upon the condion of how and when the reports
have to be generated. For example, if you want to generate a custom HTML report at the end
of execuon then you should implement IReporter interface while wring extension. But
in case you want to update a le at runme and have to print a message as and when the
tests are geng executed, then we should use the ITestListener interface.
Writing your own logger
We had earlier read about the dierent opons that TestNG provides for logging and
reporng. Now let's learn how to start using them. To start with, we will write a sample
program in which we will use the ITestListener interface for logging purposes.
Time for action – writing a custom logger
1. Open Eclipse and create a Java project with the name CustomListener and with
the following structure. Please make sure that the TestNG library is added to the
build path of the project as menoned in Chapter 1, Geng Started.
Chapter 9
[ 171 ]
2. Create a new class named SampleTest under the test.sample package and
replace the following code in it:
package test.sample;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SampleTest {
@Test
public void testMethodOne(){
Assert.assertTrue(true);
}
@Test
public void testMethodTwo(){
Assert.assertTrue(false);
}
@Test(dependsOnMethods={"testMethodTwo"})
public void testMethodThree(){
Assert.assertTrue(true);
}
}
The preceding test class contains three test methods out of which testMethodOne
and testMethodThree will pass when executed, whereas testMethodTwo is
made to fail by passing a false Boolean value to the Assert.assertTrue method
which is used for truth condions in the tests.
In the preceding class test method testMethodThree depends on
testMethodTwo.
3. Create another new class named CustomLogging under the test.logger
package and replace its code with the following code:
package test.logger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
Logging and Reports
[ 172 ]
public class CustomLogging implements ITestListener{
//Called when the test-method execution starts
@Override
public void onTestStart(ITestResult result) {
System.out.println("Test method started: "+ result.getName()+
" and time is: "+getCurrentTime());
}
//Called when the test-method execution is a success
@Override
public void onTestSuccess(ITestResult result) {
System.out.println("Test method success: "+ result.getName()+
" and time is: "+getCurrentTime());
}
//Called when the test-method execution fails
@Override
public void onTestFailure(ITestResult result) {
System.out.println("Test method failed: "+ result.getName()+ "
and time is: "+getCurrentTime());
}
//Called when the test-method is skipped
@Override
public void onTestSkipped(ITestResult result) {
System.out.println("Test method skipped: "+ result.getName()+
" and time is: "+getCurrentTime());
}
//Called when the test-method fails within success percentage
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult
result) {
// Leaving blank
}
//Called when the test in xml suite starts
@Override
public void onStart(ITestContext context) {
System.out.println("Test in a suite started: "+ context.
getName()+ " and time is: "+getCurrentTime());
}
Chapter 9
[ 173 ]
//Called when the test in xml suite finishes
@Override
public void onFinish(ITestContext context) {
System.out.println("Test in a suite finished: "+ context.
getName()+ " and time is: "+getCurrentTime());
}
//Returns the current time when the method is called
public String getCurrentTime(){
DateFormat dateFormat =
new SimpleDateFormat("HH:mm:ss:SSS");
Date dt = new Date();
return dateFormat.format(dt);
}
}
The above test class extends the ITestListener interface and denes the
overriding methods of the interface. Details of each of the methods are provided
as comments inside the previous code. Each method when executed prints the
respecve test method name or the suite name and the me when it was called.
The getCurrentTime method returns the current me in HH:mm:ss:SSS format
using the Date and DateFormat class.
4. Create a new tesng XML le under the project with name simple-logger-
testng.xml and copy the following contents onto it:
<suite name="Simple Logger Suite">
<listeners>
<listener class-name="test.logger.CustomLogging" />
</listeners>
<test name="Simple Logger test">
<classes>
<class name="test.sample.SampleTest" />
</classes>
</test>
</suite>
The preceding XML denes a simple test which considers the class test.sample.
SampleTest for test execuon. The CustomLogging class which implements
the ITestListener is added as a listener to the test suite using the listeners
tag as shown in the preceding XML.
Logging and Reports
[ 174 ]
5. Select the previous tesng XML le in Eclipse and run it as TestNG suite.
You will see the following test result in the Console window of Eclipse:
The following screenshot shows the test methods that were executed, failed,
and skipped in the test run:
What just happened?
We created a custom logger class which implements the ITestListener interface and
aached itself to the TestNG test suite as a listener. Methods of this listener class are invoked
by TestNG as and when certain condions are met in the execuon, for example, test started,
test failure, test success, and so on. Mulple listeners can be implemented and added to the
test suite execuon, TestNG will invoke all the listeners that are aached to the test suite.
Logging listeners are mainly used when we need to see the connuous status of the test
execuon when the tests are geng executed.
Chapter 9
[ 175 ]
Writing your own reporter
In the earlier secon we had seen an example of wring your custom logger and aaching
it to TestNG. In this secon we will cover, with an example, the method of wring your
custom reporter and aaching it to TestNG. To write a custom reporter class, our extension
class should implement the IReporter interface. Let's go ahead and create an example
with the custom reporter.
Time for action – writing a custom reporter
1. Open the previously created project named CustomListener and create a
package named reporter under the test package.
2. Create a new class named CustomReporter under the test.reporter package
and add the following code to it:
package test.reporter;
import java.util.List;
import java.util.Map;
import org.testng.IReporter;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.xml.XmlSuite;
public class CustomReporter implements IReporter {
@Override
public void generateReport(List<XmlSuite> xmlSuites,
List<ISuite> suites,
String outputDirectory) {
//Iterating over each suite included in the test
for (ISuite suite : suites) {
//Following code gets the suite name
String suiteName = suite.getName();
//Getting the results for the said suite
Map<String, ISuiteResult> suiteResults = suite.getResults();
for (ISuiteResult sr : suiteResults.values()) {
ITestContext tc = sr.getTestContext();
System.out.println("Passed tests for suite '" + suiteName
+ "' is:" + tc.getPassedTests().getAllResults().size());
System.out.println("Failed tests for suite '" + suiteName
+ "' is:" + tc.getFailedTests().getAllResults().size());
System.out.println("Skipped tests for suite '" + suiteName
+ "' is:" + tc.getSkippedTests().getAllResults().size());
}
}
}
}
Logging and Reports
[ 176 ]
The preceding class implements the org.testng.IReporter interface. It
implements the denion for the method generateReport of the IReporter
interface. The method takes three arguments , the rst being xmlSuite, which is
the list suites menoned in the testng XML being executed. The second one being
suites which contains the suite informaon aer the test execuon; this object
contains all the informaon about the packages, classes, test methods, and their
test execuon results. The third being the outputDirectory, which contains the
informaon of the output folder path where the reports will be generated.
The custom report prints the total number of tests passed, failed, and skipped for each
suite included in the parcular test execuon when added to TestNG as a listener.
3. Create a new le named simple-reporter-testng.xml to the project and add
the following code to it:
<suite name="Simple Reporter Suite">
<listeners>
<listener class-name="test.reporter.CustomReporter" />
</listeners>
<test name="Simple Reporter test">
<classes>
<class name="test.sample.SampleTest" />
</classes>
</test>
</suite>
The preceding XML is a testng XML conguraon le. It contains a single test
with the class test.sample.SampleTest to be considered for test execuon.
The CustomReporter class is added as a listener to the test suite using the
listeners and listener tag as dened in the previous le.
4. Select the preceding XML le and run it as TestNG test suite in Eclipse. You will see
the following test results under the Console window of Eclipse:
Chapter 9
[ 177 ]
What just happened?
We successfully created an example of wring custom reporter and aaching it to TestNG
as a listener. The preceding example shows a simple custom reporter which prints the
number of failed, passed, and skipped tests on the console for each suite included the
said test execuon. Reporter is mainly used to generate the nal report for the test
execuon. The extension can be used to generate XML, HTML, XLS, CSV, or text format
les depending upon the report requirement.
TestNG HTML and XML report
TestNG comes with certain predened listeners as part of the library. These listeners are by
default added to any test execuon and generate dierent HTML and XML reports for any
test execuon. The report is generated by default under the folder named testoutput and
can be changed to any other folder by conguring it. These reports consist of certain HTML
and XML reports that are TestNG specic.
Let's create a sample project to see how the TestNG report is generated.
Time for action – generating TestNG HTML and XML reports
1. Open Eclipse and create a Java project with the name SampleReport having the
following structure. Please make sure that the TestNG library is added to the build
path of the project as menoned in the Chapter 1, Geng Started.
2. Create a new class named SampleTest under the test package and replace the
following code in it:
package test;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SampleTest {
@Test
public void testMethodOne(){
Assert.assertTrue(true);
}
Logging and Reports
[ 178 ]
@Test
public void testMethodTwo(){
Assert.assertTrue(false);
}
@Test(dependsOnMethods={"testMethodTwo"})
public void testMethodThree(){
Assert.assertTrue(true);
}
}
The preceding test class contains three test methods out of which testMethodOne
and testMethodThree will pass when executed, whereas testMethodTwo is made
to fail by passing a false Boolean value to Assert.assertTrue method.
In the preceding class test method testMethodThree depends on testMethodTwo.
3. Select the previously created test class and run it as a TestNG test through Eclipse.
4. Now refresh the Java project in Eclipse by selecng the project and pressing the
F5 buon or right-clicking and selecng Refresh, and this will refresh the project.
You will see a new folder named test-output under the project.
5. Expand the folder in Eclipse and you will see the following les as shown in
the screenshot:
Chapter 9
[ 179 ]
6. Open index.html as shown in the preceding screenshot on your default
web browser. You will see the following HTML report:
7. Now open the le testing-results.xml in the default XML editor on
your system, and you will see the following results in the XML le:
Logging and Reports
[ 180 ]
What just happened?
We successfully created a test project and generated a TestNG HTML and XML report for the
test project. TestNG by default generates mulple reports as part of its test execuon. These
reports mainly include TestNG HTML report, TestNG emailable report, TestNG report XML,
and JUnit report XML les. These les can be found under the output report folder (in this
case test-output). These default report generaon can be disabled while running the tests
by seng the value of the property useDefaultListeners to false. This property can be
set while using the build tools like Ant or Maven as explained in the previous chapter.
Generating a JUnit HTML report
JUnit is one of those unit frameworks which were inially used by many Java applicaons as
a Unit test framework. By default, JUnit tests generate a simple report XML les for its test
execuon. These XML les can then be used to generate any custom reports as per the tesng
requirement. We can also generate HTML reports using the XML les. Ant has such a ulity
task which takes these JUnit XML les as input and generates an HTML report from it. We had
earlier learnt that TestNG by default generates the JUnit XML reports for any test execuon.
We can use these XML report les as input for generaon of a JUnit HTML report. Assuming
we already have JUnit XML reports available from the earlier execuon let's create a simple
Ant build conguraon XML le to generate an HTML report for the test execuon.
Time for action – generating a JUnit report
1. Go to the previously created Java project in Eclipse.
2. Create a new le named junit-report-build.xml by selecng the project.
3. Add the following code to the newly created le and save it:
<project name="Sample Report" default="junit-report" basedir=".">
<!-- Sets the property variables to point to respective
directories -->
<property name="junit-xml-dir" value="${basedir}/test-output/
junitreports" />
<property name="report-dir" value="${basedir}/html-report" />
<!-- Ant target to generate html report -->
<target name="junit-report">
<!-- Delete and recreate the html report directories -->
<delete dir="${report-dir}" failonerror="false"/>
<mkdir dir="${report-dir}" />
<mkdir dir="${report-dir}/Junit" />
<!-- Ant task to generate the html report.
Chapter 9
[ 181 ]
todir - Directory to generate the output reports
fileset - Directory to look for the junit xml reports.
report - defines the type of format to be generated.
Here we are using "noframes" which generates a single html
report.
-->
<junitreport todir="${report-dir}/Junit">
<fileset dir="${junit-xml-dir}">
<include name="**/*.xml" />
</fileset>
<report format="noframes" todir="${report-dir}/Junit" />
</junitreport>
</target>
</project>
The preceding XML denes a simple Ant build.xml le having a specic Ant
target named junit-report that generates a JUnit report when executed.
The target looks for the JUnit report XML les under the directory test-output/
junitreports. For the Ant conguraon le the default target to execute is
congured as junit-report.
4. Open the terminal window and go to the Java project directory in the terminal.
5. Run the command ant –buildfile junit-report-build.xml and press Enter.
6. Once executed a JUnit HTML report will be generated in the congured directory /
html-report/Junit.
Logging and Reports
[ 182 ]
7. Open the le named junit-noframes.html on your default web browser.
You will see the following HTML report:
What just happened?
In this secon we have seen how to use the JUnit XML report generated by TestNG and
generate HTML report using Ant. There are two kinds of reports that can be generated
using this method: frames and no-frames. If the report generaon is congured with
frames there will mulple les generated for each class and the main report will connect
to them through links. A no-frames report consists of a single le with all the results of
the test execuon. This can be congured by providing the respecve value to the format
aribute of the report task in Ant.
Generating a ReportNG report
We had earlier seen that TestNG provides opons to add custom listeners for logging and
reporng. These listeners can easily be added to the TestNG execuon and will be called
during the execuon or at the end of the execuon depending upon the type of listener.
ReportNG is a reporter add-on for TestNG that implements the report listener of TestNG.
ReportNG reports are beer looking reports compared to the original HTML reports. To
generate a ReportNG report we have to add the reporng class to the list of listeners of
TestNG while execung the tests. Let's see how to add ReportNG listener to TestNG and
generate a ReportNG HTML report. In the following example we will use the same Ant
build XML le used in Chapter 8, Using Build Tools, to run our tests.
Chapter 9
[ 183 ]
Time for action – generating a ReportNG report
1. Go to the earlier created Java project SampleProject in Eclipse.
2. Download ReportNG from http://reportng.uncommons.org/ download site.
3. Unzip and copy the reportng-<version>.jar and velocity-dep-
<version>.jar from the unzipped folder to the lib folder under the project.
4. Download guice from guice site https://code.google.com/p/google-
guice/downloads/list.
5. Unzip the downloaded guice zip le and copy the guice-<version>.jar to
the lib folder under the project.
6. Create a new le named testng.xml under the folder and add the following
content to it:
<suite name="Sample Suite">
<test name="Sample test">
<classes>
<class name="test.SampleTest" />
</classes>
</test>
</suite>
7. Create a new le named reportng-build.xml by selecng the project.
8. Add the following code to the newly created le and save it:
<project name="Testng Ant build" basedir=".">
<!-- Sets the property varaibles to point to respective
directories -->
<property name="report-dir" value="${basedir}/html-report" />
<property name="testng-report-dir" value="${report-dir}/TestNG-
report" />
<property name="lib-dir" value="${basedir}/lib" />
<property name="bin-dir" value="${basedir}/bin-dir" />
<property name="src-dir" value="${basedir}/src" />
<!-- Sets the classpath including the bin directory and all the
jars under the lib folder -->
<path id="test.classpath">
<pathelement location="${bin-dir}" />
<fileset dir="${lib-dir}">
<include name="*.jar" />
</fileset>
</path>
Logging and Reports
[ 184 ]
<!-- Deletes and recreate the bin and report directory -->
<target name="init">
<delete dir="${bin-dir}" />
<mkdir dir="${bin-dir}" />
<delete dir="${report-dir}" />
<mkdir dir="${report-dir}" />
</target>
<!-- Compiles the source code present under the "srcdir" and
place class files under bin-dir -->
<target name="compile" depends="init">
<javac srcdir="${src-dir}" classpathref="test.classpath"
includeAntRuntime="No" destdir="${bin-dir}" />
</target>
<!-- Defines a TestNG task with name "testng" -->
<taskdef name="testng" classname="org.testng.TestNGAntTask"
classpathref="test.classpath" />
<!--Executes the testng tests configured in the testng.xml file
-->
<target name="testng-execution" depends="compile">
<mkdir dir="${testng-report-dir}" />
<testng outputdir="${testng-report-dir}" classpathref="test.
classpath" useDefaultListeners="false" listeners="org.
uncommons.reportng.HTMLReporter">
<!-- Configures the testng xml file to use as test-suite -->
<xmlfileset dir="${basedir}" includes="testng.xml" />
<sysproperty key="org.uncommons.reportng.title"
value="ReportNG Report" />
</testng>
</target>
</project>
The preceding XML denes a simple Ant build XML le that generates a ReportNG
report when executed. The above XML is based on the build.xml le that
we covered in Chapter 8, Using Build Tools, under the Using Ant secon. The
said XML compiles and runs the TestNG tests. ReportNG is added as a listener
and the default listener of TestNG is disabled by seng a false value to the
useDefaultListeners aribute while using the testng Ant task.
9. Open the terminal window and go to the Java project directory in the terminal.
Chapter 9
[ 185 ]
10. Run the command ant -buildfile reportng-build.xml tesng execuon
and then press Enter.
11. Once executed a ReportNG HTML report will be generated in the congured
directory \html-report\TestNG-report\html under the said project
directory.
12. Go to the said directory and open the index.html le on your default web
browser. You will see the following HTML report:
13. By clicking on the Sample test link, you will see details of the test report as shown
in the following screenshot:
Logging and Reports
[ 186 ]
What just happened?
In the previous secon we learned how to generate a ReportNG HTML report for our
test execuon. We disabled the default TestNG reports in the previous Ant XML le but,
if required, we can generate both the default as well as ReportNG reports by enabling the
default report listeners. In the previous example the tle of the report is congured by seng
the property org.uncommons.reportng.title. There are other conguraon opons
that we can use while generang the report, and we will cover these in the next secon.
ReportNG conguration options
ReportNG provides dierent conguraon opons based on which the respecve HTML
report is generated. Following is a list of conguraons that are supported:
org.uncommons.reportng.coverage-report: This is congured as the link to
the test coverage report.
org.uncommons.reportng.escape-output: This property is used to turn o
the log output in reports. By default it's turned o and is not recommended to
be switched on as enabling this may require certain hacks to be implemented for
proper report generaon.
org.uncommons.reportng.frames: This property is used to generate an HTML
report with frameset and without frameset. The default value is set to true
and hence it generates HTML reports with frameset by default.
org.uncommons.reportng.locale: Used to override the localized messages in
the generated HTML report.
org.uncommons.reportng.stylesheet: This property can be used to customize
the CSS property of the generated HTML report.
org.uncommons.reportng.title: Used to dene a report tle for the generated
HTML report.
Have a go hero
Write an Ant le to congure ReportNG to generate an HTML report without any frames
for the TestNG execuon.
Chapter 9
[ 187 ]
Generating a Reporty-ng (former TestNG-xslt) report
While looking at the test report, senior managers might like to see the report in a graphical
representaon to know the status of the execuon with just a glance. Reporty-ng (formerly
called TestNG-xslt) is one such add-on report that generates a pie chart for your test execuon
with all the passed, failed, and skipped tests. This plugin uses the XSL le to convert the TestNG
XML report into the custom HTML report with a pie chart. To use this plugin we will write an
Ant target which will use the TestNG results XML le to generate the report.
Let's go ahead and write an Ant target to generate the report.
Time for action – generating a Reporty-ng report
1. Open the previously created SampleReport in Eclipse.
2. Download the Reporty-ng from the URL: https://github.com/cosminaru/
reporty-ng
At the time of writing this book the latest version available was Reporty-ng
1.2. You can download a newer version if available. Changes in the installation
process should be minor if there are any at all.
3. Unzip the downloaded zip and copy a le named testng-results.xsl from src\
main\resources onto the resources folder under the said project.
4. Copy the JARs saxon-8.7.jar and SaxonLiason.jar from the unzipped
Reporty-ng lib folder to the project lib folder.
5. Create a new Ant XML conguraon le named reporty-ng-report.xml
and paste the following code onto it:
<project name="Reporty-ng Report" default="reporty-ng-report"
basedir=".">
<!-- Sets the property variables to point to respective
directories -->
<property name="xslt-report-dir" value="${basedir}/reporty-ng/" />
<property name="report-dir" value="${basedir}/html-report" />
<property name="lib-dir" value="${basedir}/lib" />
<path id="test.classpath">
<fileset dir="${lib-dir}">
<include name="**/*.jar" />
</fileset>
</path>
Logging and Reports
[ 188 ]
<target name="reporty-ng-report">
<delete dir="${xslt-report-dir}" />
<mkdir dir="${xslt-report-dir}" />
<xslt in="${basedir}/test-output/testng-results.xml"
style="${basedir}/resources/testng-results.xsl" out="${xslt-
report-dir}/index.html">
<param name="testNgXslt.outputDir" expression="${xslt-report-
dir}" />
<param name="testNgXslt.sortTestCaseLinks" expression="true" />
<param name="testNgXslt.testDetailsFilter" expression="FAIL,
SKIP,PASS,CONF,BY_CLASS" />
<param name="testNgXslt.showRuntimeTotals" expression="true" />
<classpath refid="test.classpath" />
</xslt>
</target>
</project>
The preceding XML denes Ant build XML conguraon, it contains an Ant target
which generates the Reporty-ng report. The input path for testng results XML is
congured through the in aribute of the xslt task in Ant. The transformaon
from XML to HTML is done using the testng-results.xsl of Reporty-ng, the
locaon of which is congured by using the style aribute of the xslt task.
The output HTML name is congured using the out aribute.
Dierent conguraon parameters for Reporty-ng are congured using the param
task of Ant as shown in the preceding code.
6. Now go to the said project folder through the command terminal and type the
command ant –buildfile reporty-ng-build.xml and press Enter.
7. You will see the following console output on the terminal:
8. Now go to the congured report output folder reporty-ng (in this case) and open
the le index.html in your default browser. You will see the following test report:
Chapter 9
[ 189 ]
9. On clicking the Default suite link on the le-hand side, a detailed report of the
executed test cases will be displayed as shown in the following screenshot:
What just happened?
In the previous example we learned how to generate a Reporty-ng report using Ant.
The report is very good from a report point of view as it gives a clear picture of the
test execuon through the pie chart. The output report can be congured using
dierent conguraons, which we will cover in the next secon.
Logging and Reports
[ 190 ]
Conguration options for Reporty-ng report
As said earlier there are dierent conguraon opons that the Reporty-ng report supports
while generang the report. Following is the list of supported conguraon opons and how
they aect the report generaon:
testNgXslt.outputDir: Sets the target output directory for the HTML content.
This is mandatory and must be an absolute path. If you are using the Maven plugin,
this is set automacally so you don't have to provide it.
testNgXslt.cssFile: Species an alternave style sheet le overriding the
default sengs. This parameter is not required.
testNgXslt.showRuntimeTotals: Boolean ag indicang if the report should
display the aggregated informaon about the method duraons. The informaon
is displayed for each test case and aggregated for the whole suite. Non-mandatory
parameter, defaults to false.
testNgXslt.reportTitle: Use this seng to specify a tle for your HTML
reports. This is not a mandatory parameter and defaults to TestNG Results.
testNgXslt.sortTestCaseLinks: Indicates whether the test case links
(buons) in the le frame should be sorted alphabecally. By default they are
rendered in the order they are generated by TestNG so you should set this to
true to change this behavior.
testNgXslt.chartScaleFactor: A scale factor for the SVG pie chart in
case you want it larger or smaller. Defaults to 1.
testNgXslt.testDetailsFilter: Species the default sengs for the
checkbox lters at the top of the test details page. Can be any combinaon
(comma-separated) of: FAIL,PASS,SKIP,CONF,BY_CLASS.
Have a go hero
Write an Ant target in Ant to generate a Reporty-ng report with only Fail and Pass lter opons.
Chapter 9
[ 191 ]
Pop quiz – logging and reports
Q1. Which interface should the custom class implement for tracking the execuon status as
and when the test is executed?
1. org.testng.ITestListener
2. org.testng.IReporter
Q2. Can we disable the default reports generated by the TestNG?
1. Yes
2. No
Summary
In this chapter we have covered dierent secons related to logging and reporng with
TestNG. We have learned about dierent logging and reporng opons provided by TestNG,
wring our custom loggers and reporters and methods to generate dierent reports for
our TestNG execuon. Each of the reports have certain characteriscs and any or all of the
reports can be generated and used for test execuon depending upon the requirement.
Till now we have been using the XML conguraon methodology of dening and wring our
TestNG test suites. In the next chapter we will learn how to dene/congure the TestNG test
suite through code. This is helpful for dening the test suite at runme.
10
Creating a Test Suite through Code
In the previous chapter we covered the logging and reporting provided by
TestNG and different ways to extend the feature to write custom reporter
and loggers. In this chapter we will cover how to configure and run test suite
through code. This feature helps in configuring and running tests at runtime.
In this chapter we'll cover the following topics:
How to run TestNG programmacally
Creang a TestNG suite and running it
Parameterizaon of tests
Including and excluding tests
Dening a dependency
Running TestNG programmatically
In the earlier chapters we used the testng XML conguraon les to congure and dene
TestNG test suites. The problem with the use of XML is that they are stac les and may not
be changed at runme. Somemes we may need to create a test suite at runme, which
is based on an Excel sheet or database data. For such problems TestNG provides a feature
to dene and run TestNG tests at runme through code by using certain APIs provided by
TestNG. All the conguraons that are allowed through XML can be achieved by using the
API provided by TestNG. Let's learn more about the API by creang a simple TestNG suite
and running it programmacally.
Creang a Test Suite through Code
[ 194 ]
Time for action – running TestNG programmatically
Perform the following steps to run TestNG programmacally:
1. Create a new Java project named TestngCodeProject with the following
structure as shown in the following screenshot:
2. Create a new class named SampleTest under the test.sample package and add
the following code to it:
package test.sample;
import org.testng.annotations.Test;
public class SampleTest {
@Test
public void testMethodOne(){
System.out.println("Test method One");
}
@Test
public void testMethodTwo(){
System.out.println("Test method two");
}
}
The previous code contains a simple test class with two test methods.
These test methods print a message onto the console when executed.
3. Create another new class named SimpleTestngCode under the test.code
package and add the following code to it:
package test.code;
import java.util.ArrayList;
import java.util.List;
Chapter 10
[ 195 ]
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class SimpleTestngCode {
public void simpleTestNGTest(){
//List of xml suites to be considered for test execution
List<XmlSuite> suites = new ArrayList<XmlSuite>();
//List of classes to be considered for test execution
List<XmlClass> classes = new ArrayList<XmlClass>();
//Defines a simple xml suite with a name
XmlSuite suite = new XmlSuite();
suite.setName("Simple Config suite");
//Defines a xml test for a suite and with a said name
XmlTest test = new XmlTest(suite);
test.setName("Simple config test");
//A single xml class to be considered for execution
XmlClass clz = new XmlClass("test.sample.SampleTest");
classes.add(clz);
//Sets the list of classes to be considered for execution
for a test
test.setXmlClasses(classes);
//Adds a single suite to the list suites
suites.add(suite);
//Defining a testng instance
TestNG tng = new TestNG();
//Sets the List of xml suites to be considered for execution
tng.setXmlSuites(suites);
//Runs the configured testng tests.
tng.run();
}
public static void main(String[] args){
SimpleTestngCode smpCd= new SimpleTestngCode();
smpCd.simpleTestNGTest();
}
}
Creang a Test Suite through Code
[ 196 ]
The preceding class contains a method simpleTestNGTest, which contains
the code to dene a TestNG test using the API provided by TestNG. A test suite
is congured using dierent classes such as XmlSuite, XmlTest, and XmlClass
to dene respecve suites, tests, and classes to be included for test execuon.
Once the enre conguraon has been dened, an instance of TestNG class is
created and the list of suites to be run is set to the said instance. Once the list of
suites is set, tests are run using the run method provided by the TestNG class.
A stac void main method is used to create the instance of the said class and to
invoke the conguraon method.
4. Now select the class and run it as a Java applicaon. You will see the following
results in your Console window of Eclipse:
What just happened?
We have successfully created a simple test example where we have dened a simple test
conguraon to run a specic test class. An instance of XmlSuite is dened to congure
a suite of the testng XML. An instance of XmlTest is created to dene a test inside a
suite. The class to be included for test execuon is dened by creang an instance of
XmlClass and seng the class name to the instance. Once the enre conguraon has
been dened and congured, an instance of TestNG class is created and is then used to run
the conguraon. The enre conguraon that is allowed through XML can also be achieved
through code by using the APIs provided by TestNG. Following is a list of classes that TestNG
provides for dening an XML conguraon through code.
The list of API classes and their uses are shown in the following table:
Class name Uses
XmlSuite Defines a simple XML suite tag of the testng XML
XmlTest Describes a test tag of the testng XML
XmlPackage Describes a package tag in the testng XML
XmlClass Describes a class tag in the testng XML
Chapter 10
[ 197 ]
Class name Uses
XmlGroups Describes the groups tag of the testng XML
XmlInclude Describes an include tag of the testng XML
XmlDefine Describes a define tag of the testng XML, which is used
for defining a group of groups
XmlDependencies Describes a dependencies tag of the testng XML, which
is used for defining group dependencies
Have a go hero
Create a sample test conguraon, which contains mulple test suites in it.
Parameterization of tests
Earlier we saw a simple test conguraon to run a simple test class. In this secon
we will learn about the Parameterizaon feature of TestNG. We have already covered
Parameterizaon in our earlier chapters where tests are parameterized and the values to
the parameters are passed through the testng XML conguraon le. In this secon we
will see similar tests but we will learn about how to pass these parameter values to the tests
through code. Let's write a sample program, which shows how to pass the parameter values
to test through code.
Time for action – passing parameter values
Perform the following steps to pass parameter values:
1. Open the previously created Java project.
2. Create a new class named ParametrizedTest under the test.sample package
and add the following code to it:
package test.sample;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ParametrizedTest {
@Parameters({"suite-param-one","test-param-one"})
@Test
public void paramTestOne(String suiteParam,String testParam){
System.out.println("Test One.");
System.out.println("Suite param is: "+suiteParam);
Creang a Test Suite through Code
[ 198 ]
System.out.println("Test param is: "+testParam);
}
@Parameters({"suite-param-two","test-param-two"})
@Test
public void paramTestTwo(String suiteParam,String testParam){
System.out.println("Test Two.");
System.out.println("Suite param is: "+suiteParam);
System.out.println("Test param is: "+testParam);
}
}
The preceding code contains a simple test class with two test methods. These
test methods print a message onto the console when executed. Both the tests
accept two arguments and the values of these arguments are passed as parameters
through TestNG. Out of the two parameters that are passed, one is dened at the
suite level and the other at test level.
3. Create another new class named ParameterizedCode under the test.code
package and add the following code to it:
package test.code;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class ParameterizedCode {
public void parameterizedTest(){
List<XmlSuite> suites = new ArrayList<XmlSuite>();
List<XmlClass> classes = new ArrayList<XmlClass>();
Map<String,String> suiteParams = new HashMap<String,String>();
Map<String,String> testParams = new HashMap<String,String>();
XmlSuite suite = new XmlSuite();
suite.setName("Parameterized suite");
Chapter 10
[ 199 ]
//Defining suite level params and their values
suiteParams.put("suite-param-one", "Suite Param One");
suiteParams.put("suite-param-two", "Suite Param Two");
//Setting the params to the suite
suite.setParameters(suiteParams);
XmlTest test = new XmlTest(suite);
test.setName("Parameterized test");
//Defining test level params and their values
testParams.put("test-param-one", "Test Param One");
testParams.put("test-param-two", "Test Param Two");
//Setting the test level params
test.setParameters(testParams);
XmlClass clz = new XmlClass("test.sample.ParametrizedTest");
classes.add(clz);
test.setXmlClasses(classes);
suites.add(suite);
TestNG tng = new TestNG();
tng.setXmlSuites(suites);
tng.run();
}
public static void main(String[] args){
ParameterizedCode paramTst= new ParameterizedCode();
paramTst.parameterizedTest();
}
}
The preceding class contains a method parameterizedTest, which contains the
code to dene a TestNG test using API provided by TestNG. The parameters and their
respecve values are added to a Map instance of the key-value pair of type string
and then added to the instance of the XmlSuite and XmlTest class as shown
in the previous code. Once all the conguraon has been dened, an instance of
TestNG class is created and the list of suites to be run is set to the instance. Once the
list of suites is set, tests are run using the run method provided by the TestNG class.
A stac void main method is used to create the instance of the class and to invoke
the conguraon method.
Creang a Test Suite through Code
[ 200 ]
4. Now select the class and run it as a Java applicaon. You will see the following
results in your Console window of Eclipse:
What just happened?
We have successfully created an example for passing parameters through the XML
conguraon dened through code. The preceding example shows parameters dened
both at suite as well as test level. Similar to XML conguraon, here also the scope of the
test parameter will be limited to a specic test and not outside it, whereas suite parameter
can be accessed across mulple tests of that specic suite. Any number of parameters can
be used in a suite or test by adding them to the respecve Map instance and there is no limit
to the number of parameters that can be passed.
Include and exclude
Include and exclude is one of the most important features of TestNG, which allows tests
to be congured to include or exclude certain classes, packages, methods, and groups.
We covered this topic in earlier chapters when we were talking about the testng XML
conguraon. In this secon we will cover few similar things, but this me instead of
using a testng XML conguraon le, we will dene the conguraon through code.
We will cover a few examples to include and exclude methods and groups in a test.
Include/exclude methods
Include/exclude methods allow certain methods from a class to be included or excluded
from a test run. Let's write a sample program to learn how to congure a test through
code to include certain test methods from a class and exclude others.
Chapter 10
[ 201 ]
Time for action – including test methods
Perform the following steps to include test methods:
1. Open the previously created Java project.
2. Create a new class named IncludeExcludeMethodTest under the test.sample
package and add the following code to it:
package test.sample;
import org.testng.annotations.Test;
public class IncludeExcludeMethodTest {
@Test
public void testMethodOne(){
System.out.println("Test method one.");
}
@Test
public void testMethodTwo(){
System.out.println("Test method two");
}
@Test
public void testMethodThree(){
System.out.println("Test method three");
}
}
The preceding code contains a simple test class with three test methods.
These test methods print a message onto the console when executed.
3. Create another new class named IncludeExcludeMethodCode under the test.
code package and add the following code to it:
package test.code;
import java.util.ArrayList;
import java.util.List;
Creang a Test Suite through Code
[ 202 ]
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlInclude;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class IncludeExcludeMethodCode {
public void includeExcludeTest(){
List<XmlSuite> suites = new ArrayList<XmlSuite>();
List<XmlClass> classes = new ArrayList<XmlClass>();
XmlSuite suite = new XmlSuite();
suite.setName("Include Exclude Method suite");
XmlTest test = new XmlTest(suite);
test.setName("Include Exclude Method test");
//Test class to be included for test execution
XmlClass clz = new XmlClass("test.sample.
IncludeExcludeMethodTest");
//Test methods to be included
XmlInclude methodOne= new XmlInclude("testMethodOne");
XmlInclude methodTwo= new XmlInclude("testMethodTwo");
//Creating a list of included methods and adding the methods
instances to it
List<XmlInclude> includes = new ArrayList<XmlInclude>();
includes.add(methodOne);
includes.add(methodTwo);
//Setting the included methods for the class
clz.setIncludedMethods(includes);
classes.add(clz);
test.setXmlClasses(classes);
suites.add(suite);
TestNG tng = new TestNG();
tng.setXmlSuites(suites);
tng.run();
Chapter 10
[ 203 ]
}
public static void main(String[] args){
IncludeExcludeMethodCode testConfig= new
IncludeExcludeMethodCode();
testConfig.includeExcludeTest();
}
}
The preceding class contains a method includeExcludeTest, which contains
the code to dene a TestNG test. An instance of XmlSuite is created to dene a
testng test suite. The included class for test execuon is congured by creang an
instance of XmlClass and seng the class name to be included to it. An instance
of XmlInclude is created with the name of the methods to be included for test
execuon. These test methods are then added to a list and the list is then added
to the class for conguring the included methods.
A stac void main method is used to create the instance of the class and to invoke
the conguraon method.
4. Now select the class and run it as a Java applicaon. You will see the following
results in your Console window of Eclipse:
What just happened?
We have successfully created a testng conguraon for including certain test methods to
test execuon through code. As you can see, the previous code only has conguraon for
including methods and not for excluding methods. For excluding methods, TestNG does not
provide an explicit API class such as XmlInclude. For excluding methods, the respecve
method names have to be added to a list and then added to the set of excluded methods
of the respecve class using the method setExcludedMethods.
Creang a Test Suite through Code
[ 204 ]
Have a go hero
Having gone through this secon, feel free to aempt the following:
Create a sample test conguraon, which excludes certain methods from the test
class in a test execuon
Create a sample test conguraon to include and exclude test methods using
regular expressions
Include/exclude groups
In the previous secon we wrote a sample program to include methods to test execuon.
In this secon we will see how to include and exclude groups in test execuon. We will write
a program to dene a TestNG conguraon for test execuon for including and excluding
certain groups from the test execuon.
Time for action – including/excluding groups
Perform the following steps to include/exclude groups:
1. Open the previously created Java Project.
2. Create a new class named IncludeExcludeGroupTest under the test.sample
package and add the following code to it:
package test.sample;
import org.testng.annotations.Test;
public class IncludeExcludeGroupTest {
@Test(groups={"group-one"})
public void testMethodOne(){
System.out.println("Test method one of group-one");
}
@Test(groups={"group-one","group-two"})
public void testMethodTwo(){
System.out.println("Test method two of group-one and group-
two");
}
@Test(groups={"group-one"})
public void testMethodThree(){
Chapter 10
[ 205 ]
System.out.println("Test method three of group-one");
}
}
The preceding code contains a simple test class with three test methods. These
test methods print a message onto the console when executed. All three of the
test methods belong to the group group-one and one method testMethodTwo
belongs to group-two too.
3. Create another new class named IncludeExcludeGroupCode under the test.
code package and add the following code to it:
package test.code;
import java.util.ArrayList;
import java.util.List;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class IncludeExcludeGroupCode {
public void includeExcludeTest(){
List<XmlSuite> suites = new ArrayList<XmlSuite>();
List<XmlClass> classes = new ArrayList<XmlClass>();
XmlSuite suite = new XmlSuite();
suite.setName("Include Exclude Group suite");
XmlTest test = new XmlTest(suite);
test.setName("Include Exclude Group test");
XmlClass clz = new XmlClass("test.sample.
IncludeExcludeGroupTest");
classes.add(clz);
test.setXmlClasses(classes);
//Including and excluding groups
test.addIncludedGroup("group-one");
test.addExcludedGroup("group-two");
suites.add(suite);
Creang a Test Suite through Code
[ 206 ]
TestNG tng = new TestNG();
tng.setXmlSuites(suites);
tng.run();
}
public static void main(String[] args){
IncludeExcludeGroupCode testConfig= new
IncludeExcludeGroupCode();
testConfig.includeExcludeTest();
}
}
The preceding class contains a method, includeExcludeTest, which contains
the code to dene a TestNG test. An instance of XmlSuite is created to dene a
testng test suite. The included class for test execuon is congured by creang
an instance of XmlClass and seng the class name to be included to it. The test
groups are included and excluded from a test using the addIncludedGroups and
addExcludedGroups methods of the XmlTest class as shown in the previous code.
A stac void main method is used to create the instance of the conguraon class
and to invoke the conguraon method.
4. Now select the class and run it as a Java applicaon. You will see the following
results in your Console window of Eclipse:
What just happened?
We have successfully created a testng conguraon for including and excluding certain
groups from test execuon through code. The previous code shows how to congure the test
to include and exclude groups at runme. The name of every group to be included or excluded
for test execuon has to be added using the addIncludedGroups and addExcludedGroups
methods provided by the instance of the XmlTest class. When tests are run, TestNG
automacally includes and excludes congured groups from the test execuon.
Chapter 10
[ 207 ]
Have a go hero
Now it's me for you to test your understanding of what you have learned by creang a
sample test conguraon, which includes a package to the test.
Dependency test
Dependency test is another feature of TestNG where group dependency can be dened using
the testng XML conguraon. You can also achieve the same conguraon using the API
provided by TestNG. In this secon we will write a sample program, which contains mulple
test methods that belong to dierent groups. Through code we will dene dependency of a
group onto another group and will run the tests using this conguraon.
Time for action – conguring a dependency test
Perform the following steps to congure a dependency test:
1. Open the previously created Java project.
2. Create a new class named DependencyTest under the test.sample package and
add the following code to it:
package test.sample;
import org.testng.annotations.Test;
public class DependencyTest {
@Test(groups={"group-one"})
public void testMethodOne(){
System.out.println("Test method one of group-one");
}
@Test(groups={"group-one"})
public void testMethodTwo(){
System.out.println("Test method two of group-one");
}
@Test(groups={"group-one"})
public void testMethodThree(){
System.out.println("Test method three of group-one");
}
@Test(groups={"group-two"})
public void testMethodFour(){
Creang a Test Suite through Code
[ 208 ]
System.out.println("Test method Four of group-two");
}
@Test(groups={"group-two"})
public void testMethodFive(){
System.out.println("Test method Five of group-two");
}
}
The preceding code contains a simple test class with ve test methods. These test
methods print a message onto the console when executed. Out of the ve test
methods three belong to group-one and the other two belong to group-two.
3. Create another new class named DependencyCode under the test.code
package and add the following code to it:
package test.code;
import java.util.ArrayList;
import java.util.List;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class DependencyCode {
public void dependencyTest(){
List<XmlSuite> suites = new ArrayList<XmlSuite>();
List<XmlClass> classes = new ArrayList<XmlClass>();
XmlSuite suite = new XmlSuite();
suite.setName("Dependency suite");
XmlTest test = new XmlTest(suite);
test.setName("Dependency test");
XmlClass clz = new XmlClass("test.sample.DependencyTest");
classes.add(clz);
test.setXmlClasses(classes);
//Defining an xml dependency where "group-one" depends on
"group-two"
Chapter 10
[ 209 ]
test.addXmlDependencyGroup("group-one", "group-two");
suites.add(suite);
TestNG tng = new TestNG();
tng.setXmlSuites(suites);
tng.run();
}
public static void main(String[] args){
DependencyCode testConfig= new DependencyCode();
testConfig.dependencyTest();
}
}
The preceding class contains a method dependencyTest, which contains the
code to dene a TestNG. An instance of XmlSuite is dened to dene a testng
test suite. The included class for test execuon is congured by creang an
instance of XmlClass and seng the class name to be included to it. An XML
dependency of group-one depending upon group-two is dened by calling the
addXmlDependencyGroup method on the instance of XmlTest.
A stac void main method is used to create the instance of the conguraon class
and to invoke the conguraon method.
4. Now select the class and run it as a Java applicaon. You will see the following
results in your Console window of Eclipse:
Creang a Test Suite through Code
[ 210 ]
What just happened?
We have successfully created a testng conguraon for dening an XML dependency
through code. A dependency of group-one on group-two is dened. This can be veried
by looking at the console output. The previous example shows a conguraon of a single
group dependency only, but in case we have to dene a mulgroup dependency, we can
do so by passing the dependent group names in a string separated by a space, for example,
group-two group-three group-four.
Pop quiz – creating a test suite through code
Q1. Which of the following classes is not provided as part of the TestNG API?
1. XmlSuites
2. XmlTest
3. XmlClass
Q2. Can we dene mulple test suites for a specic test run through code?
1. Yes
2. No
Q3. Which of the following classes can be used to include and exclude a package?
1. XmlPackage
2. XmlPackages
3. XmlClasses
4. XmlClass
Summary
In this chapter we have covered the feature of conguring or dening tests and test
suites in TestNG. We have covered dierent opons of including classes and methods
groups. Also we have wrien a sample program to pass dierent parameters to the test
at suite or test level. We have also seen how to dene a group dependency through code
and run it. This feature is very useful when the tests have to be congured or dened at
runme based on some external data.
In the next chapter we will cover how to run your exisng JUnit tests through TestNG
and how to migrate your exisng JUnit tests to TestNG.
11
Migrating from JUnit
In the previous chapter we learned how to configure and execute TestNG tests
through code. We had learned about different ways to configure and run the
TestNG tests at runtime. In this chapter we will cover how to run the existing
JUnit tests through TestNG and how to migrate your existing JUnit
tests to TestNG.
In this chapter we'll cover the following topics:
Running your JUnit Tests through TestNG
Running JUnit tests along with TestNG through Ant
Migrang from JUnit to TestNG
Running your JUnit tests through TestNG
Many of the old test frameworks use JUnit as the tesng and execuon framework but,
with the advantages that TestNG provides over JUnit forces the teams to think about
moving to TestNG. This can be a tedious task and may take a huge eort depending upon
the number of exisng JUnit test cases. In case you want to move to using TestNG and are
sll thinking how to run your exisng JUnit tests, you can very well achieve it thorough
TestNG. TestNG provides an in-built ulity to run your exisng JUnit-3 or JUnit-4 tests.
Let's rst write a sample JUnit test and run it. Aer this we will see how to run the said
test through TestNG.
Migrang from JUnit
[ 212 ]
Time for action – writing a JUnit test
1. Create a Java project named JunitProject with the following structure:
2. Download the latest JUnit JAR from the following URL:
http://sourceforge.net/projects/junit/.
3. Paste the following JAR to the lib folder as shown in the structure in
the preceding image.
4. Select the said JAR in Eclipse and do right-click and navigate to Build Path | Add to
Build Path.
5. Now create a new class le named JunitSampleTest under the package test.
sample.junit and add the following code to it:
package test.sample.junit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class JunitSampleTest {
@BeforeClass
public static void beforeClassMethod(){
System.out.println("Junit before class method");
}
@Before
public void beforeMethod(){
System.out.println("Junit before method");
}
Chapter 11
[ 213 ]
@Test
public void testMethod(){
System.out.println("Junit test method");
}
@After
public void afterMethod(){
System.out.println("Junit after method");
}
@AfterClass
public static void afterClassMethod(){
System.out.println("Junit after class method");
}
}
The preceding class contains ve methods out of which two are BeforeClass and
AfterClass annotated methods, two are Before and After annotated method,
and one is a test method. The preceding class is a simple JUnit test class and each
of the methods present in it outputs a console message when executed.
6. Select the said class le and do a right-click, and navigate to Run As | JUnit Test.
This will run the said class le as a simple JUnit Test. You can see the following
result on the Eclipse console:
What just happened?
In the preceding example we have created a sample JUnit test class which contains a single
test method in it. The said JUnit test class is executed through Eclipse to see how it executes
the methods which are contained in it. This test class will act as a sample test for us in the
coming secons and we will migrate the said test class to a TestNG test class going forward.
Migrang from JUnit
[ 214 ]
Running your JUnit Tests through TestNG using the testng XML
TestNG can be congured to run JUnit tests using the testng XML conguraon le.
The said conguraon can be done at both suite and test tag level in a testng XML
conguraon le. Let's write a simple testng XML conguraon for running the JUnit
class wrien previously through TestNG.
Time for action – running JUnit tests through TestNG
1. Open the previously created Java project in Eclipse.
2. Create a new le named simple-junit-test.xml and paste the following code
to it:
<suite name="Simple JUnit Suite">
<test junit="true" name="Simple JUnit test">
<classes>
<class name="test.sample.junit.JunitSampleTest" />
</classes>
</test>
</suite>
The prreceding suite contains a simple test in it. The test includes the
JunitSampleTest class for the test execuon. TestNG is congured to execute
the JUnit tests in the said class by seng the value of the aribute junit to true.
3. Select the previously created XML conguraon le and run it as a TestNG test suite.
You will see the following test result on the Eclipse Console window:
Chapter 11
[ 215 ]
What just happened
We created a sample testng XML conguraon le to run JUnit tests through TestNG.
Aribute junit is used along with the test tag to congure TestNG. This aribute
can also be used along with the suite tag. We can run both JUnit-3 and JUnit-4 tests
using the said conguraon. JUnit-based classes can only be run using the preceding
conguraon, if we have any TestNG test classes they won't get executed. In the next
secon we will cover an example of how to run both JUnit and TestNG tests together
through the testng XML conguraon.
Running JUnit and TestNG tests together with TestNG XML
In the previous example we have seen how to congure and run JUnit tests using the
testng XML conguraon le.
In this secon we will write a testng XML conguraon le which will run both JUnit
as well as TestNG tests in a single test suite.
Time for action – running JUnit and TestNG tests together
1. Open the previously created Java project in Eclipse.
2. Create a new class named TestngSampleTest under the package test.sample.
testng and add the following code to it:
package test.sample.testng;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestngSampleTest {
@BeforeMethod
public void beforeMethod(){
System.out.println("Testng before method");
}
@Test
public void testMethod(){
System.out.println("Testng test method");
}
@AfterMethod
Migrang from JUnit
[ 216 ]
public void afterMethod(){
System.out.println("Testng after method");
}
}
3. Create a new le named junit-testng-test.xml and paste the following
code to it:
<suite name="Junit Testng Suite">
<test junit="true" name="Junit test">
<classes>
<class name="test.sample.junit.JunitSampleTest" />
</classes>
</test>
<test name="Testng test">
<classes>
<class name="test.sample.testng.TestngSampleTest" />
</classes>
</test>
</suite>
The preceding suite contains two tests in it. One of the tests includes the
JunitSampleTest class for the said test execuon and another test includes
the TestngSampleTest. TestNG is congured to execute the JUnit tests for XML
test that include junit test class by seng the value of the aribute junit to true,
whereas the other XML test is a simple test.
4. Select the said XML conguraon le and run it as a TestNG test suite.
You will see the following test result on the Eclipse Console window:
Chapter 11
[ 217 ]
What just happened?
We have created a sample testng XML conguraon le to run JUnit and TestNG tests
together through TestNG. Aribute junit is used along with the test tag for the test
containing the JUnit test class to congure TestNG to run the said junit tests. The other
test is a simple TestNG test that contains a testng test class for the test execuon. There is
another way for execung your JUnit and TestNG tests together through build tool; in the
next secon we will cover the same.
Have a go hero
Create a testng XML conguraon for both JUnit and TestNG tests by including packages
and methods in the test execuon.
Running JUnit tests along with TestNG through Ant
In the earlier secon we have seen how to run JUnit through TestNG using testng XML
conguraon. We have also seen how to run both JUnit and TestNG tests together. But that
was a simple test that we covered in the example. Consider a scenario where a project has
hundreds of exisng JUnit tests and the team has decided to move to TestNG for its beer
features. It will take a lot of me to migrate exisng JUnit tests to TestNG and by that me
the team has to run exisng tests along with the new TestNG tests. This can be achieved by
conguring TestNG to run both kinds of tests while using a build tool like Ant or Maven.
Almost all of the test frameworks use some or the other build tools to build and run their
unit tests. Let's run both TestNG and JUnit tests together through the Ant build tool.
Time for action – running JUnit and TestNG tests through Ant
1. Open the previously created Java project in Eclipse.
2. Add the testng library JAR downloaded earlier to the lib folder.
3. Create a new le named build.xml under the said project and add the following
code to it:
<project name="Testng Ant build" basedir=".">
<!-- Sets the property varaibles to point to respective
directories -->
<property name="report-dir" value="${basedir}/html-report" />
<property name="testng-report-dir" value="${report-dir}/TestNG-
report" />
<property name="lib-dir" value="${basedir}/lib" />
<property name="bin-dir" value="${basedir}/bin-dir" />
Migrang from JUnit
[ 218 ]
<property name="src-dir" value="${basedir}/src" />
<!-- Sets the classpath including the bin directory and all the
jars under
the lib folder -->
<path id="test.classpath">
<pathelement location="${bin-dir}" />
<fileset dir="${lib-dir}">
<include name="*.jar" />
</fileset>
</path>
<!-- Deletes and recreate the bin and report directory -->
<target name="init">
<delete dir="${bin-dir}" />
<mkdir dir="${bin-dir}" />
<delete dir="${report-dir}" />
<mkdir dir="${report-dir}" />
</target>
<!-- Compiles the source code present under the "srcdir" and
place class files under bin-dir -->
<target name="compile" depends="init">
<javac srcdir="${src-dir}" classpathref="test.classpath"
includeAntRuntime="No" destdir="${bin-dir}" />
</target>
<!-- Defines a TestNG task with name "testng" -->
<taskdef name="testng" classname="org.testng.TestNGAntTask"
classpathref="test.classpath" />
<!-- Include class files containg the text "Test" in their
names. -->
<fileset id="mixed-test" dir="${src-dir}">
<include name="**/*Test.*" />
</fileset>
<!-- Executes the testng tests configured in the xtestng.xml
file -->
<target name="testng-execution" depends="compile">
<mkdir dir="${testng-report-dir}" />
Chapter 11
[ 219 ]
<testng mode="mixed" classfilesetref="mixed-test"
outputdir="${testng-report-dir}" classpathref="test.classpath"
useDefaultListeners="true">
</testng>
</target>
</project>
The preceding is an Ant build.xml le which is taken from Chapter 8, Using Build
Tools. The preceding build.xml le will compile and run both JUnit and TestNG
tests together. Test class les are included by using a name based regular search
using the fileset task of Ant. This fileset id is then added to TestNG execuon
by using the aribute classfilesetref. TestNG has been congured to execute
both JUnit and TestNG tests by seng the aribute value of mode to mixed.
4. Open the command prompt and go to the respecve Java project path in the system.
5. Under the respecve Java project folder, type the command ant testing-
execution and press Enter.
6. Ant will compile and execute your TestNG tests. You will see the following screen:
Migrang from JUnit
[ 220 ]
What just happened?
We have successfully created an Ant build XML conguraon le for running JUnit and
TestNG tests. TestNG is congured to run both kinds of tests using the mode aribute while
using the testng Ant task. If the value of the said aribute is set to mixed it will run both
JUnit and TestNG tests as part of the same project. The classes can exist together under the
same package. This conguraon will help to convert your exisng JUnit tests to TestNG tests
incrementally without giving up on the test execuon. Currently Maven doesn't have an
in-built ulity to run such a conguraon, but in case you want to run the said conguraon
in Maven, you can do so by wring the said Ant task in Maven and calling it for execuon.
Migrating from JUnit to TestNG
In case you are migrang from JUnit to TestNG there are certain things that need to be taken
care of in your exisng test classes and test methods. The following table will help you with
making such changes:
Use-case JUnit-4 JUnit-3 TestNG Comment
A Test
method
@Test Test-method
name starting
with "test"
@Test In case you are
migrating from
JUnit-4, you just
need to change
the import. If you
are migrating
from JUnit-3
annotation all the
test methods with
@Test
Run before
each test
method
@Before Method with
name "setup"
@BeforeMethod Change name and
import
Run after
each test
method
@After Method with
name "cleanup"
@AfterMethod Change Name and
import
Run before
each test
class
@
BeforeClass
N/A @BeforeClass Change the
import. Also JUnit
needs the said
method to be a
static method,
whereas in Testng
it can be static or
non-static method
Chapter 11
[ 221 ]
Use-case JUnit-4 JUnit-3 TestNG Comment
Run after
each test-
class
@AfterClass N/A @AfterClass Change the
import. Also JUnit
needs the said
method to be a
static method,
whereas in
TestNG it can
be static or
non-static method
Disabling a
test
@Ignore N/A @Test(enable=
"false")
Need to change
the annotation
Other than the things that are menoned in the preceding table, we also need to take
care of the Assert statements of JUnit. There is a dierence between the occurrence of the
argument between JUnit and TestNG. In JUnit the asseron expected value is followed by the
actual value, whereas in TestNG it's reversed. To solve this, TestNG provides a class named
AssertJunit where the asseron methods match the order of JUnit asseron methods.
Let's convert the earlier menoned JUnit example to a TestNG test using the previous table.
Time for action – converting a JUnit test to a TestNG test
1. Select the previously created Java project.
2. Now create a new class le named JunitToTestngTest under the package test.
sample.testng and add the following code to it:
package test.sample.testng;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class JunitToTestngTest {
@BeforeClass
public static void beforeClassMethod(){
System.out.println("Junit before class method");
}
@BeforeMethod
public void beforeMethod(){
System.out.println("Junit before method");
Migrang from JUnit
[ 222 ]
}
@Test
public void testMethod(){
System.out.println("Junit test method");
}
@AfterMethod
public void afterMethod(){
System.out.println("Junit after method");
}
@AfterClass
public static void afterClassMethod(){
System.out.println("Junit after class method");
}
}
The preceding class is the same sample JUnit test class that is converted to TestNG
test class. As shown in the previous table the import of the annotaons are changed
to testng based annotaons. The Before and After annotated JUnit methods are
changed to the BeforeMethod and AfterMethod annotaon of testng. Whereas
for the Test annotated test method we have just changed the import statement.
3. Now run the said class as a TestNG test. You will see the following output in the
Eclipse Console window:
Chapter 11
[ 223 ]
What just happened?
We have successfully converted an exisng JUnit test into a TestNG test and have run it
successfully. The import for the Test annotaon is changed to use TestNG package. Before
and After annotaons were changed to BeforeMethod and AfterMethod annotaons
of TestNG, whereas for the BeforeClass and AfterClass annotaons, the import
statements were changed to use the TestNG packages. As you can see from the previous
test results, the output is same as the output of the test when it was executed as JUnit test.
Pop quiz – migrating from JUnit
Q1. Which of the following aributes have to be used when conguring TestNG to run
JUnit tests while using tesng XML conguraon?
1. mode
2. junit
3. mixed
Q2. What should be the value of the aribute mode while conguring TestNG to run
both JUnit and TestNG tests together?
1. junit-testng
2. junit
3. mixed
Q3. Which class of TestNG should we use while migrang our exisng JUnit tests
having Assert statements to TestNG?
1. Assert
2. JunitAssert
3. AssertJunit
Migrang from JUnit
[ 224 ]
Summary
In the current chapter we have covered dierent methods of running JUnit tests through
TestNG. We had even learned ways to run both TestNG and JUnit tests together through
TestNG XML conguraon or by using build tools. TestNG supports the running of both
JUnit-3 and JUnit-4 tests in it. This helps dierent teams who are migrang from their
exisng JUnit tests to TestNG without actually running both the tests separately.
In the coming chapter we will cover unit and funconal tesng using TestNG. Under
Unit tesng we will cover mocking and dierent mocking techniques using TestNG. Under
funconal tesng we will cover basics of selenium and how to use selenium with TestNG.
12
Unit and Functional Testing
In the previous chapter we learned about how to run existing tests of JUnit
through TestNG and how to migrate from JUnit to TestNG. We also covered
different points considered for migration and the changes that are required to
be done as a part of the migration. In this chapter we will cover topics related
to unit and functional testing using TestNG.
In this chapter we'll cover the following topics:
Unit tesng with TestNG
Mocking and dierent mocking techniques
Mocking with TestNG
Funconal tesng
TestNG with Selenium
Unit testing with TestNG
Before we go ahead with unit tesng with TestNG, let’s get a brief idea of what unit tesng
is. Unit tesng refers to the pracce/process of tesng units, parts, and secons of a code.
Unit tesng helps to verify whether our funcons work as they are expected to work. With
unit tesng we can verify whether our funcon supports some expected inputs and returns
some expected outputs. Wring or developing unit tests also helps in idenfying future bugs
at the earlier stages of development itself. Unit tesng also helps in improving the quality of
the code that is developed.
Unit and Funconal Tesng
[ 226 ]
TestNG as you have being reading in past chapters can be used for unit tesng and helps
in wring or developing unit test cases. Let’s create a sample test project with a test class
containing unit tests for the ArrayList class.
Time for action – unit testing with TestNG
1. Create a new Java Project named SimpleUnitTestProject in Eclipse with the
folder structure shown in the following screenshot:
2. Open the le ListUnitTest.java and add the following snippet to it:
package org.test.sampletests;
import java.util.ArrayList;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ListUnitTest {
ArrayList<String> listObj = new ArrayList<String>();
@BeforeClass
public void beforeClass(){
listObj.add("Sample-0");
listObj.add("Sample-1");
listObj.add("Sample-2");
}
@Test
public void verifyDataBasedOnIndex(){
String data = listObj.get(0);
Assert.assertEquals(data, "Sample-0","Data dont match");
}
@Test(expectedExceptions=IndexOutOfBoundsException.class)
public void verifyForWrongIndex(){
listObj.get(4);
}
Chapter 12
[ 227 ]
@Test
public void verifySize(){
Assert.assertTrue(listObj.size()==3,"Size dont match");
}
}
The preceding code contains a few sample unit tests to verify the ArrayList
implementaon. It contains three test-methods, which verify the get and size
method of the list. The BeforeClass annotated method add a data set to the
list whereas the dierent test-methods verify the dierent scenarios, such as
verifying whether the correct data is returned when passing a correct index,
excepon is thrown when fetching a value at the wrong index, and vericaon
of the size based on data stored.
3. Select the said class le and run it as a TestNG test. You will see the following
screenshot as output in the Console window:
What just happened?
We have successfully created a sample test class, which contains some unit test-methods
to test an ArrayList class implementaon. The tests verify few of the condions of the
ArrayList class. If you noced that there are dierent methods from the Assert class
being used in the program. The assert helps in idenfying the success and failure condions
of a test. In case of failure these assert statements fail in the test and mark them as failed in
the test-report. We will be talking about asseron in our next secon.
Have a go hero
Write unit tests for clear, contains, and remove methods of the ArrayList class.
Unit and Funconal Tesng
[ 228 ]
Assertion with TestNG
Asseron plays an important part while performing unit tesng. Asseron helps you to check
or verify the success of condions in your test. If the condions don’t sasfy, it will stop the
test execuon of the said test and mark it as failing.
Asserons are basically code blocks that can be placed in test cases to verify certain
condions. Most of the unit test frameworks provide implementaons for using asserons
in the tests. TestNG supports asseron of a test using the Assert class which is part of the
library. The following table describes few of the methods and their usage that are available
with the Assert class in testng:
Method Usage
assertEquals(boolean actual,
boolean expected)
Takes two Boolean arguments and checks
whether both are equal else fails the test.
assertEquals(boolean actual,
boolean expected, java.lang.
String message)
Takes two Boolean arguments and checks
whether both are equal else fails the test
with the given message.
assertEquals(java.lang.String
actual, java.lang.String
expected, java.lang.String
message)
Takes two string arguments and verifies that
both are equal. In case they are not equal this
method fails the test with the given message.
assertEquals(java.util.
Collection actual, java.util.
Collection expected, java.
lang.String message)
Takes two collection objects and verifies both
of the collections contain the same elements
and in the same order. Else this fails the test
with the given message.
assertTrue(boolean condition,
java.lang.String message)
Verifies that the passed condition variable is
true else fails the test with the given message.
assertFalse(boolean condition,
java.lang.String message)
Verifies that the passed condition variable is
false else fails the test with the given message.
fail(java.lang.String message) Directly fails a test with the given message.
This method is mainly used while handling
exception conditions and when we have
failed the test forcefully.
Mocking
Mocking is mainly used while performing unit tesng. While wring unit tests, the code
under test may depend on another class object or class method in the code. This dependent
code may or may not be available for tesng. To isolate the behavior of the code under test
from that of the dependent code we use the mocking technique.
Chapter 12
[ 229 ]
Mocking allows users to create mock objects and behaviors that the code under test is
dependent upon. Mock objects basically simulate the behavior of the dependent code
so that the unit tesng of the code under test can be completed.
Different mocking strategies
There are a lot of mocking ulies available online for mocking while wring unit tests
developed in Java. Each has some advantages and disadvantages when compared to
other. Few of the mocking ulies are named as follows:
Jmock
Mockito
EasyMock
PowerMock
Jmockit
Each of the preceding menoned mocking libraries provide abilies to mock objects,
methods, and behaviors. Each of them has their own advantages and disadvantages
depending upon what we are using them for. In this chapter we will cover two of the
most commonly used mocking libraries Jmock and Mockito. We will write down
examples for each of them and will use them along with TestNG.
Mocking with TestNG
TestNG don’t have an inbuilt mocking implementaon in it, but we can use any third-party
implementaons that are based on Java; and which don’t rely on a parcular kind of unit
test execuon framework to be used along with it. You had already read about mocking
and dierent mocking techniques that are available in the market. In this secon we will
take two of the most commonly used mocking frameworks Jmock and Mockito, and write
sample programs using them in TestNG.
Jmock
Jmock was one of the inial mocking frameworks that were developed to support unit
tesng and TDD based development approach. It provides all the basic features required
for mocking, such as mocking objects, methods, return values and so on. It was developed
inially for JUnit but with recent modicaons it can be used with any unit test framework.
In the following example we will cover a basic example of wring a unit test methods for a
sample code, and mocking certain unavailable methods through Jmock. We will use TestNG for
wring unit tests and maven for building and running the tests. We are using maven, because
maven will automacally download the dependent libraries required for compilaon.
Unit and Funconal Tesng
[ 230 ]
Time for action – using JMock with TestNG
1. Create a new Java Project named JmockTesProject in eclipse with the folder
and le structure shown in the following screenshot:
2. Open the le AreaFinder.java and add the following code to it:
package main.java.org.test.mocking;
public class AreaFinder {
private final Calculator calculator;
public AreaFinder(Calculator calculator) {
this.calculator = calculator;
}
public double getAreaOfCircle(double radius) {
if(radius > 0)
return calculator.multiply(Math.PI, calculator.
square(radius));
else if(radius <0)
throw new IllegalArgumentException();
else
return 0;
}
}
The preceding class le is a sample le which calculates the area of a circle
when we call the method getAreaOfCircle of the said class. The calculaon
is done by internally invoking the Calculator class methods.
Chapter 12
[ 231 ]
3. Open the le Calculator.java and add the following code to it:
package main.java.org.test.mocking;
public interface Calculator {
double multiply(double a, double b);
double square(double a);
}
This is an interface which declares mulple and square methods. In this example
none of the classes will be implemenng this interface and we will be mocking
the said interface implementaon for tesng the AreaFinder class le.
4. Open the le AreaFinderJmockTest.java and add the following snippet to it:
package test.java.org.test.mocking;
import main.java.org.test.mocking.AreaFinder;
import main.java.org.test.mocking.Calculator;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.Sequence;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AreaFinderJmockTest{
//Creating a context object for macking purpose
private final Mockery context = new Mockery();
private AreaFinder areaFinder;
/*
* Creating a mock object using mocking context earlier created
* for the Calculator interface as there is no implementation for
* it existing.
*/
private Calculator calculator = context.mock(Calculator.class);
@BeforeMethod
public void setUp() {
areaFinder = new AreaFinder(calculator);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void
getAreaOfCircleShouldThrowIllegalArgumentException
ForNegativeRadius() {
Unit and Funconal Tesng
[ 232 ]
areaFinder.getAreaOfCircle(-1.2);
}
@Test
public void getAreaOfSquareShouldReturnExpectedValue() {
final double radius = 4.1;
final double radiusSquare = 5.3;
final double expectedArea = 10.9;
/*
* Mocking the return values for the calculator methods
* using the context object
*/
context.checking(new Expectations() {
final Sequence sequence = context.sequence("circle-area-
sequence");
{//Mocking the square method in calculator and returning a
particular value
oneOf(calculator).square(radius);
will(returnValue(radiusSquare));
inSequence(sequence);
}
{
oneOf(calculator).multiply(Math.PI, radiusSquare);
will(returnValue(expectedArea));
inSequence(sequence);
}
});
Assert.assertEquals(areaFinder.getAreaOfCircle(radius),
expectedArea, 0);
}
}
The AreaFinderJmockTest class contains the unit test methods for the
AreaFinder class. There are two test methods present in this class, one that
veries that an IllegalArgumentException is thrown when a negave radius
is passed to calculate the area, and the other one veries the posive condion
of geng the expected area value for a parcular radius. As there are internal calls
to the Calculator interface methods square and multiple these methods are
mocked to return specied values using Jmock.
5. Open the pom.xml le and add the following code snippet to it:
<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 http://
maven.apache.org/xsd/maven-4.0.0.xsd">
Chapter 12
[ 233 ]
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>jmock</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<!-- Source directory configuration -->
<sourceDirectory>src</sourceDirectory>
<plugins>
<!-- Following plugin executes the testng tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
</plugin>
<!-- Compiler plugin configures the java version to be used
for compiling the code -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.jmock</groupId>
<artifactId>jmock</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.3.1</version>
</dependency>
</dependencies>
</project>
Unit and Funconal Tesng
[ 234 ]
This a maven conguraon le for compiling and running the TestNG tests. Most of
this is taken from the sample maven project created under the Using maven secon
in the Chapter 8, Using Build Tools. Few extra dependencies, such as jmock and
junit are added to the said conguraon. Jmock sll has some dependency on
JUnit, hence the said library is added as dependency in the conguraon.
6. Open the terminal/command window and go to the root folder of the preceding
Java project.
7. Type and run the command mvn test, you will see the following screenshot as
output in the console:
What just happened?
We have successfully created an example of Jmock using TestNG. As you can see from the
preceding example, Jmock is used to mock the calls to the methods of the Circle interface
and return parcular values based on certain value arguments. These methods are internally
called inside the AreaFinder class, such as the getAreaOfCircle method. When a call is
made to these mocked methods Jmock returns the congured values to the calling funcon,
in this case it’s the getAreaOfCircle method. In case you want to know more about
Jmock and how to use it, you can go to its ocial website http://www.jmock.org/.
Chapter 12
[ 235 ]
Have a go hero
Add a new method to the AreaFinder class menoned earlier to get the area of the circle
and write units tests for it.
Mockito
Mockito is another mocking framework, which provides similar capabilies to Jmock and is
wrien in much a similar way to Jmock. The tests using Mockito as a mocking framework
are much more clean and readable. Let’s write a simple maven based java project, which
contains the same code that needs to be unit tested. We will write similar unit tests but this
me we will use Mockito as a mocking framework. This will give us a clear idea about how
Mockito is dierent from Jmock.
Time for action – using Mockito
1. Create a new Java Project named MockitoTestProject in eclipse with the folder
and le structure as shown in the following screenshot:
2. Copy the code for the Calculator.java le from the previously created
project on to the le Calculator.java in the current project. You can also replace
the exisng le with the one from the previously created project as they
are both the same.
3. Copy the code for the AreaFinder.java le from the earlier secon in to the le
AreaFinder.java in the current project. You can also replace the exisng le with
the one from the previously created project as they are both the same.
4. Open the le AreaFinderMockitoTest and add the following code to it:
package test.java.org.test.mocking;
import main.java.org.test.mocking.AreaFinder;
import main.java.org.test.mocking.Calculator;
Unit and Funconal Tesng
[ 236 ]
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.MockitoAnnotations;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AreaFinderMockitoTest{
@InjectMocks private AreaFinder areaFinder;
@Mock private Calculator calculator ;
@BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
areaFinder = new AreaFinder(calculator);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void
getAreaOfCircleShouldThrowIllegalArgumentException
ForNegativeRadius() {
areaFinder.getAreaOfCircle(-1.2);
}
@Test
public void getAreaOfSquareShouldReturnExpectedValue() {
final double radius = 4.1;
final double radiusSquare = 5.3;
final double expectedArea = 10.9;
//Mocking the Calculator methods and returning particular values.
when(calculator.square(radius)).thenReturn(radiusSquare);
when(calculator.multiply(Math.PI, radiusSquare)).
thenReturn(expectedArea);
Assert.assertEquals(areaFinder.getAreaOfCircle(radius),
expectedArea, 0);
}
}
The preceding class contains the unit test methods for the AreaFinder class.
There are two test-methods present in this class, one that veries that an
IllegalArgumentException is thrown when a negave radius is passed to
calculate the area, and the other one veries the posive condion of geng
the expected area value for a parcular radius. As there are internal calls to the
Calculator interface methods, such as square and multiple, these methods
are mocked to return specied values using Mockito.
Chapter 12
[ 237 ]
5. Open the pom.xml le and add the following code snippet into it:
<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 http://
maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>mockito</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<!-- Source directory configuration -->
<sourceDirectory>src</sourceDirectory>
<plugins>
<!-- Following plugin excutes the testng tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
</plugin>
<!-- Compiler plugin configures the java version to be used
for compiling the code -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.3.1</version>
</dependency>
</dependencies>
</project>
Unit and Funconal Tesng
[ 238 ]
This a maven conguraon le for compiling and running TestNG tests in our project.
Most of this is taken from the sample maven project created under the Using Maven
secon in Chapter 8, Using Build Tools. A few extra dependencies such as mockito
are added to the conguraon.
6. Open the terminal/command window and go to the root folder of the preceding
Java project.
7. Type and run the command mvn test and you will see the following output in
the console:
What just happened?
We have successfully created a sample test class, which uses Mockito for mocking and ran
it through TestNG. As you can see from the preceding example, the said unit tests are the
same tests that we had performed for Jmock. You can clearly see the dierence in the way
the tests were wrien using Jmock and using Mockito. As you can see with Mockito tests
are simpler to read and write. Test methods are mocked using the when and thenReturn
methods provided by Mockito. More detailed informaon on Mockito can be obtained by
going to its ocial site at https://code.google.com/p/mockito/.
Chapter 12
[ 239 ]
Functional testing
Funconal tesng is a process of tesng soware or a hardware based on its design or
specicaon. It involves tesng dierent features and funconalies provided by soware
or hardware based on its requirement. It mainly consists of integraon scenarios to verify
that the feature works well with other features and does not fail in any condion.
In the soware industry funconal tesng plays a key role in the life cycle of tesng as it
conrms the product requirement and design specicaons, and helps in idenfying bugs
in the soware. Funconal tesng is performed manually as well as through automaon
tools. Automaon may involve wring unit test methods for the applicaon code as well as
the use of some funconal automaon tools. Funconal test methods are dierent from that
of unit test methods. They are dierent in a way that unit test methods are meant to test an
independent part of the code, whereas funconal tests are wrien to check the funconality
and may involve interacon between dierent secons of code. When it comes to funconal
automaon tools there is a huge list of such tools in the market. These tools help in
automang the funconal tests and hence reduces the manual and periodic tesng eort.
The following is a list of funconal tesng automaon tools that are available in the market:
Selenium/Webdriver
Raonal funconal tester
Sikuli
Quick Test Professional
SilkTest
In the next secon we will give an example of Selenium/webdriver, which is one of
the most famous funconal tesng tools being used along with TestNG framework
to funconally automate a Google search.
TestNG with Selenium
Nowadays Selenium is one of the most famous funconal tesng tools used for web based
applicaon tesng. Selenium has a lot of features inbuilt in it, which helps web applicaon
tesng teams to automate their funconal test cases. The following is a list of a few such
features of Selenium:
Provides record and playback capabilies
Supports mulple browsers and browser versions. For example, Firefox, Chrome,
IE, Opera, and so on
Unit and Funconal Tesng
[ 240 ]
Inbuilt support for Android and iOS tesng
Inbuilt grid setup for seng up a Selenium server grid for simultaneous or
parallel execuon of tests
Easy API for easy use and enhancement
These are just few advantages of using Selenium, it has a vast use and has been used by
numerous teams worldwide for automang their funconal tests. Majority of people use
Selenium along with TestNG due to the numerous features provided by TestNG. One of
the important features being the multhreaded execuon of tests, this feature helps the
funconal tests to execute simultaneously on mulple browsers or even mulple parallel
execuons on the same type of browser. In the following example we will cover a sample
Selenium test which will execute the same test in parallel using TestNG.
Before proceeding with the following example, please make sure that the Firefox browser
is installed onto your system. You can download the latest version of Firefox from the URL
http://www.mozilla.org/en-US/firefox/new/.
Time for action – using Selenium with TestNG
1. Create a new Java project in Eclipse with name SeleniumSampleTest and
with project structure shown in the following screenshot:
2. Open the SampleSeleniumTest le and add the following code snippet to it:
package test.java.org.sample.selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
Chapter 12
[ 241 ]
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class SampleSeleniumTest {
WebDriver driver;
@BeforeMethod
public void beforeMethod(){
//Initializing the selenium webdriver object
driver = new FirefoxDriver();
}
@Test
public void googleTest(){
//Opening the google page
driver.navigate().to("http://www.google.com");
//Finding the search field and entering text to it.
driver.findElement(By.cssSelector("input[name=’q’]"))
.sendKeys("TestNG");
WebDriverWait wait = new WebDriverWait(driver, 30);
//Waiting for the search list to be populated.
List<WebElement> results=wait.until(ExpectedConditions.presenc
eOfAllElementsLocatedBy(By.cssSelector("h3.r")));
//Getting the text of the first search result.
String searchResult=results.get(0).getText();
//Verifying the text of first search test result with the
expected text
Assert.assertEquals(searchResult,"TestNG - Welcome");
}
@AfterMethod
public void afterMethod(){
//Quitting the browser.
driver.quit();
}
}
The preceding test class contains a sample test for tesng a search in Google.
The preceding test enters text TestNG in the Google search box and waits for
the search list to be populated with search results. Once the search list is populated
it gets the text of the rst search result and veries whether it matches it with tle
of testng site TestNG—Welcome.
Unit and Funconal Tesng
[ 242 ]
3. Add a le named testng.xml to the current project and add the following code
snippet to it:
<suite name="Selenium Suite" parallel="tests" thread-count="2">
<test name="Selenium test - 1">
<classes>
<class name="test.java.org.sample.selenium.
SampleSeleniumTest" />
</classes>
</test>
<test name="Selenium test - 2">
<classes>
<class name="test.java.org.sample.selenium.
SampleSeleniumTest" />
</classes>
</test>
</suite>
The preceding le is a testng conguraon le, which contains two tests in it.
Both the tests include the same test class SampleSeleniumTest for the tests.
The suite is congured to execute in a multhreaded mode by using the aribute
thread-count at suite level. The conguraon for thread execuon is congured
so that each test in the suite is run in a separate thread.
4. Open the le pom.xml and add the following code snippet to it:
<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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>jmock</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<!-- Source directory configuration -->
<sourceDirectory>src</sourceDirectory>
<plugins>
<!-- Following plugin excutes the testng tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
<configuration>
Chapter 12
[ 243 ]
<!-- Suite testng xml file to consider for test
execution -->
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<!-- Compiler plugin configures the java version to be used
for compiling the code -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.3.1</version>
</dependency>
</dependencies>
</project>
The preceding code is the maven conguraon to compile and run our tests.
The conguraon is the same conguraon covered under the Using maven secon
in Chapter 9, Using Build Tools. There is a dependency of Selenium-java-2.33.0,
which is been added to the conguraon le.
5. Now go to the command prompt/terminal and navigate to the preceding Java
project folder.
Unit and Funconal Tesng
[ 244 ]
6. Type the command mvn test and run it. Maven will download all the required
jars and will compile and run our test. You will see two browsers opening
simultaneously, which opens the Google page, searches for the text TestNG,
and then closes the window. You will also see the following output in the
command prompt for your test execuon:
What just happened?
We have successfully created a sample funconal test for a Google search and veried the
test result using Selenium. The said test is implemented as a testng test and TestNG is
used for execung the said Selenium test. In this example we have used Selenium to execute
the funconal test on two instances of the Firefox browser simultaneously. This is just an
example of how we can use Selenium with TestNG featuring one of the advantages of using
TestNG. This feature can also be used for execung same set of tests in mulple browsers
simultaneously. Also the test suite conguraon and report extension are few of the features
of TestNG that provide a lot of advantages when used with Selenium.
Chapter 12
[ 245 ]
Pop quiz – unit and functional testing
Q1. Which of the following is the correct representaon of an assert method in TestNG?
1. Assert.assertEquals(String actual, String expected)
2. Assert.assertEquals(String expected, String actual)
Q2. "Unit tesng is the process of tesng integrated modules and code".
Is the statement correct?
1. Yes
2. No
Q3. "Using mocking we can mock (fake) unimplemented method calls and return
custom values". Is the statement correct?
1. Yes
2. No
Summary
In this chapter we have covered dierent topics related to unit tesng and funconal tesng
through TestNG. We have learned about unit tesng, mocking, and the dierent mocking
strategies available in the market. We have also seen some praccal examples of using
mocking frameworks, such as Jmock and Mockito along with TestNG.
At the end of this chapter we have learned about funconal tesng and dierent
automaon tools available in the market to automate funconal tesng. We also
wrote a sample program in TestNG using Selenium, which is one of the most famous
web automaon tools in the market.
Unit and funconal tesng play a key role in the lifecycle of soware development as
they together help in reducing the me taken to idenfy the bug, and hence improving
the development life cycle.
TestNG is a great test automaon framework that can be used for mulple kinds of tesng
whether it be unit, integraon, or even funconal. Over the chapters we have covered
almost all the basic features provided by TestNG with examples, and by the end of this
chapter you may have got hands on with TestNG and its features.
Pop Quiz Answers
Chapter 1, Getting Started
Pop quiz – about TestNG
Q1 1
Q2 1
Chapter 2, Understanding testng.xml
Pop quiz – TestNG XML
Q1 1
Q2 2
Q3 2
Pop Quiz Answers
[ 248 ]
Chapter 3, Annotations
Pop quiz – annotations
Q1 3
Q2 3
Q3 2
Q4 2
Q5 3
Q6 3
Chapter 4, Groups
Pop quiz – groups
Q1 1
Q2 1
Q3 2
Q4 3
Chapter 5, Dependencies
Pop quiz – dependencies
Q1 1
Q2 2
Chapter 6, The Factory Annotation
Pop quiz – the Factory annotation
Q1 1
Q2 2
Pop Quiz Answers
[ 249 ]
Chapter 7, Parallelism
Pop quiz – parallelism
Q1 3
Q2 3
Chapter 8, Using Build Tools
Pop quiz – build tools
Q1 2
Q2 3
Q3 1
Chapter 9, Logging and Reports
Pop quiz – logging and reports
Q1 1
Q2 1
Chapter 10, Creating a Test Suite through Code
Pop quiz – creating a test suite through code
Q1 1
Q2 1
Q3 1
Pop Quiz Answers
[ 250 ]
Chapter 11, Migrating from JUnit
Pop quiz – migrating from JUnit
Q1 2
Q2 3
Q3 3
Chapter 12, Unit and Functional Testing
Pop quiz – unit and functional testing
Q1 1
Q2 2
Q3 1
Index
Symbols
@AerClass 52
@AerGroups 52
@AerMethod 52
@AerSuite 52
@AerTest 52
@BeforeClass 52
@BeforeGroups 52
@BeforeMethod 52
@BeforeSuite 52
@BeforeTest 52
@DataProvider 52
@Factory 53
@Factory annotaon
about 125, 139
used, for execung dependency test 135, 136
using 125
using, with DataProvider 129, 130
@Parameters 53
@Test 53
A
aerClass method 148, 153
alwaysRun aribute 62
annotaons. See TestNG annotaons
Ant
about 156
advantages 161
installing 156, 157
JUnit tests, running with TestNG 217-220
terminologies 157
URL 157
used, for running TestNG tests 157-161
using 157
Ant, build process
compile 160
init 160
Ant, terminologies
project 157
target 157
tasks 157
ant testng-execuon command 160
ArrayList class 226
Assert.assertTrue method 171, 178
Assert class
methods 228
asseron
about 228
with TestNG 228
aributes, Test annotaon
about 62
alwaysRun 62
dataProvider 62
dataProviderClass 62
dependsOnGroups 62
dependsOnMethods 62
descripon 62
enabled 62
expectedExcepons 62
groups 62
meOut 62
[ 252 ]
B
Before and Aer annotaon opons
about 53
extending 59-61
running 54-58
beforeClass method 148, 153
beforeTest method 149, 150
bin directory 157, 162
build automaon
about 155
advantages 156
build tools
Ant 156
Gradle 156
Maven 156
build.xml le 156
C
classes-test-testng.xml le 147
command prompt
used, for execung testng.xml 26-28
compile opon 160
conguraon opons, ReportNG report
about 186
org.uncommons.reportng.escape-output 186
org.uncommons.reportng.frames 186
org.uncommons.reportng.locale 186
org.uncommons.reportng.stylesheet 186
org.uncommons.reportng.tle 186
conguraon opons, Reporty-ng report
testNgXslt.chartScaleFactor 190
testNgXslt.cssFile 190
testNgXslt.outputDir 190
testNgXslt.reportTitle 190
testNgXslt.showRunmeTotals 190
testNgXslt.sortTestCaseLinks 190
testNgXslt.testDetailsFilter 190
Console window 141, 144, 147, 150, 152
custom logger
wring 170-174
custom reporter
wring 175-177
D
data-driven tests 7
DataProvider
about 78
in dierent class 81, 82
Test annotaon, using on class 79, 80
using, with @Factory annotaon 129, 130
dataProvider aribute 62
dataProviderClass aribute 62
DataProvider test
about 131
creang 132, 133
default group
about 98
assigning, to set of tests 98-100
working 98
Dependencies, Maven 163
dependency test
about 105, 207
conguring 207-209
depending on mulple tests, creang 108, 109
depending on single test, creang 106, 107
execung, with @Factory annotaon 135, 136
inherited dependency test 109
regular expressions, using 115, 117
running sequenally 137
dependent groups 112
dependsOnGroups aribute 62
dependsOnMethods aribute 62
descripon aribute 62
E
Eclipse
conguring, for testng.xml 29, 30
TestNG, installing 8
URL 8
used, for execung testng.xml 28
used, for running TestNG group 88
enabled aribute 62
excepon test
about 66
verifying message, wring 68, 69
working 66
wring 66, 67
[ 253 ]
excludedgroups opon, Ant 161
excludedgroups opon, Maven 166
expectedExcepons aribute 62
F
factory 125
factory methods
parameters, passing to test classes 127-129
factory test
about 131
creang 126, 127, 133, 134
features, Selenium 239, 240
features, TestNG
about 7
Aer annotaon opon 7
beer reporng 8
data-driven tesng 7
dependent groups 7
dependent methods 7
groups 7
Mulple Before opon 7
multhreaded execuon 7
Open API 8
parameterizaon, of test methods 7
test suite denion 7
XML based test conguraon 7
funconal tesng
about 239
automaon tools 239
G
getCurrentTime method 173
groups
excluding 204-206
including 204-206
groups aribute 62
groups opon, Ant 161
groups opon, Maven 166
I
Id value 144, 147
include/exclude methods
about 200
using 45
include/exclude packages
about 42
using 42
including/excluding groups
performing, testng XML used 93, 95
IndependentTestThreading class 151, 152
inherited dependency test
creang 110, 111
init opon 160
Installaons
Ant 156, 157
Maven 162
invocaonCount aribute 151, 152
J
Java project
about 13
creang 13, 14
Jmock
about 229
URL 234
using, with TestNG 230-234
JUnit 6
JUnit and TestNG tests
running, simultaneously 215-217
JUnit HTML report
about 180, 182
generang 180-182
JUnit migraon
to TestNG 220, 221
JUnit tests
converng, to TestNG test 221-223
running, through TestNG 211
running, with TestNG 217-220
wring 212, 213
L
Listeners 170
listeners opon, Ant 161
listeners opon, Maven 166
logging
about 169
custom logger 170
[ 254 ]
M
main method 209
Maven
about 162
conguraons 166
installing 162
URL 162, 163
used, for running TestNG tests 163-166
using 163
Maven, conguraons
excludedgroups opon 166
groups opon 166
listeners opon 166
outputdir opon 166
parallel opon 166
testname opon 166
threadCount opon 166
meOut opon 166
Maven, features
Dependencies 163
Plugins 163
project 163
maven-surere-plugin 165
MetaGroups 100
mocking
about 228
strategies 229
with TestNG 229
mocking ulies
EasyMock 229
Jmock 229
Jmockit 229
Mockito 235
PowerMock 229
Mockito
about 235
URL 238
using 235-238
mulgroup dependency
about 119
test, creang 108
using, in XML 119-121
multhreaded execuon
advantages 153
multhreaded mode 140
multhreaded program
parallel test, wring 140-142
wring 140
mvn command 162
mvn test command 164
N
NUnit 6
O
outputdir opon, Ant 161
outputdir opon, Maven 166
P
parallel
test classes, running 144-148
test methods, running 142-144
tests, running inside suite 148-151
parallel aribute 148, 150
Parallelism
about 140
advantages 153
parallel opon, Ant 161
parallel opon, Maven 166
parallel test
wring 140-142
parameterizaon
about 73
oponal values, providing 76-78
through testng.xml 73-76
Plugins, Maven 163
pom.xml le 163, 164
project, Ant 157
project, Maven 163
R
regular expressions
about 46
using 46-49
using, for dependency 121, 122
using, in dependency test 115-117
using, in testng XML 96, 97
[ 255 ]
Reporters 170
ReportNG report
about 182
conguraon opons 186
generang 183-186
Reporty-ng report
about 187
conguraon opons 190
generang 187-189
S
SampleBuildTest class 158
sample project, test suite
creang 34
test, creang with classes 34-36
test, creang with methods 38
test, creang with package, class, and test
method 40, 41
test, creang with packages 36-38
SampleTestClassOne class 145, 147
SampleTestClassTwo class 146, 147
Sample Test link 185
SampleTestMethod class 142, 143
SampleTestSuite class 148, 150
Selenium
about 239
features 239, 240
using, with TestNG 240-244
setExcludedMethod 203
SimpleClass class 140
simple group dependency
about 117
using, in XML 117-119
single test method dependency
creang 106, 107
soware development life cycle (SDLC) 6
T
target, Ant 157
tasks, Ant 157
test
disabling 64
Test annotaon
about 62, 151
aributes 62
using, on class 63, 64
test automaon 6
test classes
running, in parallel 144-148
test, dependent on group
creang 112, 113
test, dependent on methods from dierent class
creang 113-115
tesng 5
tesng.xml le 160
test methods
disabling 65
including 201-203
running, in parallel 142-144
testname opon, Ant 161
testname opon, Maven 166
TestNG
about 6, 170, 226
asserons 228
DataProvider 78
default group 98
dependency test 105, 135
downloading 8
excepon test 66
features 7
HTML 177
include/exclude methods 45
include/exclude packages 42
including/excluding groups 93
installing, onto Eclipse 9-12
JMock, using with 230-234
JUnit, migrang to 220, 221
JUnit tests, running through 211
JUnit tests, running with 217-220
Listeners 170
mocking implementaon 229
mulple tests, creang 31
parameterizaon 73
prerequisite 8
regular expressions 95
Reporters 170
report, generang, ways 170
running programmacally 194-197
Selenium, using with 240-244
me test 69
used, for unit tesng 226, 227
XML-based dependency conguraon 117
XML report 177
[ 256 ]
TestNG annotaons
@AerClass 52
@AerGroups 52
@AerMethod 52
@AerSuite 52
@AerTest 52
@BeforeClass 52
@BeforeGroups 52
@BeforeMethod 52
@BeforeSuite 52
@BeforeTest 52
@DataProvider 52
@Factory 53
@Factory annotaon 125
@Listeners 53
@Parameters 53
@Test 53
about 52
Before and Aer annotaon, running 54-58
Test annotaon 62
TestNG class
creang 16, 17
testng-execuon opon 160
TestNG group
about 100
running 87
running, Eclipse used 88, 89
running, testng.xml used 101, 102
running, testng XML used 89, 90
TestNG HTML
generang 177-180
TestNG plugin opons
class 19
group 19
method 19
package 19
suite 19
TestNG task
conguraons 161
TestNG task, conguraons
excludedgroups opon 161
groups opon 161
listeners opon 161
outputdir opon 161
parallel opon 161
testname opon 161
threadCount opon 161
meOut opon 161
TestNG test
Java project, creang 13-16
JUnit test, converng to 221-223
running 18
running, through Eclipse 18, 19
TestNG class, creang 16, 17
wring 13
TestNG tests
running, Ant used 157-161
testng.xml
about 23
creang, with mulple tests 31-33
regular expressions, using 96, 97
running, Eclipse used 28
running, through command prompt 26, 27
used, for creang test suite 24
used, for running TestNG group 89
TestNG XML
JUnit and TestNG tests, running
simultaneously 215-217
JUnit Tests, running through TestNG 214, 215
testng.xml le 158
TestNG XML report
generang 177-180
TestNG-xslt. See Reporty-ng
testNgXslt.chartScaleFactor 190
testNgXslt.cssFile 190
testNgXslt.outputDir 190
testNgXslt.reportTitle 190
testNgXslt.showRunmeTotals 190
testNgXslt.sortTestCaseLinks 190
testNgXslt.testDetailsFilter 190
test package 158
test.parallelism package 140, 145-148, 151
tests
grouping 85
running, independent in threads 151, 152
running, inside suite in parallel 148-151
tests, belonging to group
creang 86, 87
tests, having mulple groups
creang 91, 93
tests parameteriazon
parameter values, passing 197-200
[ 257 ]
test suite
creang, by excluding test method 45, 46
creang, by excluding test package 43, 44
creang, by including test package 42, 43
creang, testng.xml used 24, 25
creang, with regular expression 46, 47
running 26
thread-count aribute 141, 144, 150
threadCount opon, Ant 161
threadCount opon, Maven 166
Thread.currentThread.getId() method 141-46
threadPoolSize aribute 151
threads
independent tests, running 151, 152
meOut aribute 62, 151
meOut opon, Ant 161
meOut opon, Maven 166
me test
about 69
wring, at suite level 70, 71
wring, at test-method level 71-73
U
unit tesng
about 225
with TestNG 226, 227
X
XML-based dependency conguraon
about 117
mulgroup dependency 119
regular expression, using 121, 122
simple group dependency 117
XmlClass class 196
XmlDene class 197
XmlDependencies class 197
XmlGroups class 197
XmlInclude class 197
XmlPackage class 196
XmlSuite class 196
XmlTest class 196
Thank you for buying
TestNg Beginner's Guide
About Packt Publishing
Packt, pronounced 'packed', published its rst book "Mastering phpMyAdmin for Eecve
MySQL Management" in April 2004 and subsequently connued to specialize in publishing
highly focused books on specic technologies and soluons.
Our books and publicaons share the experiences of your fellow IT professionals in adapng
and customizing today's systems, applicaons, and frameworks. Our soluon based books
give you the knowledge and power to customize the soware and technologies you're
using to get the job done. Packt books are more specic and less general than the IT books
you have seen in the past. Our unique business model allows us to bring you more focused
informaon, giving you more of what you need to know, and less of what you don't.
Packt is a modern, yet unique publishing company, which focuses on producing quality,
cung-edge books for communies of developers, administrators, and newbies alike. For
more informaon, please visit our website: www.packtpub.com.
About Packt Open Source
In 2010, Packt launched two new brands, Packt Open Source and Packt Enterprise, in order
to connue its focus on specializaon. This book is part of the Packt Open Source brand,
home to books published on soware built around Open Source licences, and oering
informaon to anybody from advanced developers to budding web designers. The Open
Source brand also runs Packt's Open Source Royalty Scheme, by which Packt gives a royalty
to each Open Source project about whose soware a book is sold.
Writing for Packt
We welcome all inquiries from people who are interested in authoring. Book proposals
should be sent to author@packtpub.com. If your book idea is sll at an early stage and you
would like to discuss it rst before wring a formal book proposal, contact us; one of our
commissioning editors will get in touch with you.
We're not just looking for published authors; if you have strong technical skills but no wring
experience, our experienced editors can help you develop a wring career, or simply get
some addional reward for your experse.
Swing Extreme Testing
ISBN: 978-1-84719-482-4 Paperback: 328 pages
The Extreme Approach to Complete Java
Applicaon Tesng
1. Learn Swing user interface tesng strategy
2. Automate tesng of components usually
thought too hard to test automacally
3. Praccal guide with ready-to-use examples
and source code
4. Based on the authors’ experience developing
and tesng commercial soware
JavaScript Unit Testing
ISBN: 978-1-78216-062-5 Paperback: 190 pages
Your comprehensive and praccal guide to eciently
performing and automang JavaScript unit tesng
1. Learn and understand, using praccal
examples, synchronous and asynchronous
JavaScript unit tesng
2. Cover the most popular JavaScript Unit Tesng
Frameworks including Jasmine, YUITest, QUnit,
and JsTestDriver
3. Automate and integrate your JavaScript Unit
Tesng for ease and eciency
Please check www.PacktPub.com for information on our titles
Selenium Testing Tools Cookbook
ISBN: 978-1-84951-574-0 Paperback: 326 pages
Over 90 recipes to build, maintain, and improve test
automaon with Selenium WebDriver
1. Learn to leverage the power of Selenium WebDriver
with simple examples that illustrate real world
problems and their workarounds
2. Each sample demonstrates key concepts allowing
you to advance your knowledge of Selenium
WebDriver in a praccal and incremental way
3. Explains tesng of mobile web applicaons
with Selenium Drivers for plaorms such as
iOS and Android
Web Services Testing with soapUI
ISBN: 978-1-84951-566-5 Paperback: 440 pages
Build high quality service-oriented soluons by
learning easy and e cient web services tesng
with this praccal, hands-on guide
1. Become more procient in tesng web services
included in your service-oriented soluons
2. Find, analyze, reproduce bugs eecvely by
adhering to best web service tesng approaches
3. Learn with clear step-by-step instrucons and
hands-on examples on various topics related
to web services tesng using soapUI
Please check www.PacktPub.com for information on our titles