Pro Apache JMeter - Web Application Performance Testing (PDFDrive)
Pro Apache JMeter - Web Application Performance Testing (PDFDrive)
JMeter
Web Application Performance Testing
—
Sai Matam
Jagdeep Jain
www.allitebooks.com
Pro Apache JMeter
Web Application Performance Testing
Sai Matam
Jagdeep Jain
www.allitebooks.com
Pro Apache JMeter: Web Application Performance Testing
Sai Matam Jagdeep Jain
Pleasonton, California, USA Dewas, Madhya Pradesh, India
ISBN-13 (pbk): 978-1-4842-2960-6 ISBN-13 (electronic): 978-1-4842-2961-3
DOI 10.1007/978-1-4842-2961-3
Library of Congress Control Number: 2017951240
Copyright © 2017 by Sai Matam and Jagdeep Jain
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage
and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or
hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject
to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material
contained herein.
Cover image by Freepik (www.freepik.com)
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Celesting Suresh John
Development Editor: Laura Berendson
Technical Reviewer: Nitesh Kumar Jain
Coordinating Editor: Sanchita Mandal
Copy Editor: Kezia Endsley
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
[email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit http://www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web
page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to readers
on GitHub via the book’s product page, located at www.apress.com/978-1-4842-2960-6. For more detailed
information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
www.allitebooks.com
I dedicate this book to my wife, Jyothi, for inspiration, support, and for single-handedly running
around kids and various chores while I tapped at the keyboard.
—Sai Matam
I dedicate this book to my parents, who always motivated me to do things differently,
and to my sisters and my wife; without their support, I would not be able to manage a tight
schedule on and off work.
—Jagdeep Jain
www.allitebooks.com
Contents at a Glance
■
■Chapter 1: Foundation������������������������������������������������������������������������������������������� 1
■
■Chapter 2: Performance Testing Primer���������������������������������������������������������������� 3
■
■Chapter 3: Your First JMeter Test������������������������������������������������������������������������ 13
■
■Chapter 4: JMeter Test Script Recorder�������������������������������������������������������������� 25
■
■Chapter 5: JMeter Test Plan Components����������������������������������������������������������� 35
■
■Chapter 6: Distributed Testing��������������������������������������������������������������������������� 167
■
■Chapter 7: JMeter Best Practices���������������������������������������������������������������������� 179
■
■Chapter 8: Troubleshooting JMeter������������������������������������������������������������������� 197
■
■Chapter 9: JMeter Plugins��������������������������������������������������������������������������������� 211
■
■Chapter 10: JMeter Recipes������������������������������������������������������������������������������ 221
■
■Chapter 11: Case Study: Digital Toys Inc.���������������������������������������������������������� 243
■
■Chapter 12: Performance Dashboard���������������������������������������������������������������� 303
■
■Chapter 13: Appendix A: Setting Up JMeter������������������������������������������������������ 315
■
■Chapter 14: Appendix B: Setting Up Digital Toys Inc.���������������������������������������� 327
Index��������������������������������������������������������������������������������������������������������������������� 333
www.allitebooks.com
Contents
■
■Chapter 1: Foundation������������������������������������������������������������������������������������������� 1
Why Performance Testing?����������������������������������������������������������������������������������������������� 1
Why JMeter?�������������������������������������������������������������������������������������������������������������������� 2
■
■Chapter 2: Performance Testing Primer���������������������������������������������������������������� 3
Performance Testing�������������������������������������������������������������������������������������������������������� 3
Response Time��������������������������������������������������������������������������������������������������������������������������������������� 3
Throughput��������������������������������������������������������������������������������������������������������������������������������������������� 4
Utilization������������������������������������������������������������������������������������������������������������������������������������������������ 5
Robustness��������������������������������������������������������������������������������������������������������������������������������������������� 5
Scalability����������������������������������������������������������������������������������������������������������������������������������������������� 5
User Perception�������������������������������������������������������������������������������������������������������������������������������������� 5
Cost�������������������������������������������������������������������������������������������������������������������������������������������������������� 5
vii
www.allitebooks.com
■ Contents
Conclusion���������������������������������������������������������������������������������������������������������������������� 12
■
■Chapter 3: Your First JMeter Test������������������������������������������������������������������������ 13
Components of a JMeter Test����������������������������������������������������������������������������������������� 13
Test Plan����������������������������������������������������������������������������������������������������������������������������������������������� 13
Thread Group���������������������������������������������������������������������������������������������������������������������������������������� 13
Controller���������������������������������������������������������������������������������������������������������������������������������������������� 14
Sampler������������������������������������������������������������������������������������������������������������������������������������������������ 14
Listener������������������������������������������������������������������������������������������������������������������������������������������������� 14
Timer���������������������������������������������������������������������������������������������������������������������������������������������������� 14
Assertions��������������������������������������������������������������������������������������������������������������������������������������������� 14
Config Element������������������������������������������������������������������������������������������������������������������������������������� 14
Pre-Processors������������������������������������������������������������������������������������������������������������������������������������� 15
Post-Processors����������������������������������������������������������������������������������������������������������������������������������� 15
viii
www.allitebooks.com
■ Contents
■
■Chapter 6: Distributed Testing��������������������������������������������������������������������������� 167
Distributed Testing Using JMeter��������������������������������������������������������������������������������� 167
Prerequisites���������������������������������������������������������������������������������������������������������������� 167
Configuration���������������������������������������������������������������������������������������������������������������� 168
Running the Test����������������������������������������������������������������������������������������������������������� 170
GUI Mode���������������������������������������������������������������������������������������������������������������������� 171
Non-GUI Mode�������������������������������������������������������������������������������������������������������������� 172
RMI Port������������������������������������������������������������������������������������������������������������������������ 172
Sample Sender Mode��������������������������������������������������������������������������������������������������� 173
Unreachable Remote Hosts������������������������������������������������������������������������������������������ 176
Limitations�������������������������������������������������������������������������������������������������������������������� 177
Conclusion�������������������������������������������������������������������������������������������������������������������� 177
■
■Chapter 7: JMeter Best Practices���������������������������������������������������������������������� 179
HTTP Request Defaults������������������������������������������������������������������������������������������������� 179
Follow Redirects����������������������������������������������������������������������������������������������������������� 180
Cookie Manager����������������������������������������������������������������������������������������������������������� 182
Cache Manager������������������������������������������������������������������������������������������������������������ 185
JMeter Using Maven���������������������������������������������������������������������������������������������������� 185
Passing Variables Across Thread Groups��������������������������������������������������������������������� 187
Running Parallel Thread Groups����������������������������������������������������������������������������������� 191
Using External File for Parameterizing User Login������������������������������������������������������� 192
Customizing Properties������������������������������������������������������������������������������������������������ 194
Monitor JMeter Resource Usage���������������������������������������������������������������������������������� 194
Standard Test Plan Templates�������������������������������������������������������������������������������������� 195
Conclusion�������������������������������������������������������������������������������������������������������������������� 196
xi
www.allitebooks.com
■ Contents
■
■Chapter 8: Troubleshooting JMeter������������������������������������������������������������������� 197
Ensure Permissions������������������������������������������������������������������������������������������������������ 197
Log File������������������������������������������������������������������������������������������������������������������������� 197
Log Level���������������������������������������������������������������������������������������������������������������������� 198
HTTP Protocol Logs������������������������������������������������������������������������������������������������������ 199
GUI Logs����������������������������������������������������������������������������������������������������������������������� 199
Clear GUI Logs�������������������������������������������������������������������������������������������������������������� 200
Remote Host Exception������������������������������������������������������������������������������������������������ 200
Connect Exception�������������������������������������������������������������������������������������������������������� 201
Solving Proxy Servers Problems���������������������������������������������������������������������������������� 202
HTTP Basic Authentication������������������������������������������������������������������������������������������� 204
Using HTTP Header Manager��������������������������������������������������������������������������������������� 205
Using the HTTP Authorization Manager������������������������������������������������������������������������ 206
Debug Test Faster��������������������������������������������������������������������������������������������������������� 207
Out of Memory Error����������������������������������������������������������������������������������������������������� 209
Conclusion�������������������������������������������������������������������������������������������������������������������� 210
■
■Chapter 9: JMeter Plugins��������������������������������������������������������������������������������� 211
PerfMon������������������������������������������������������������������������������������������������������������������������ 211
Download the Plugin��������������������������������������������������������������������������������������������������������������������������� 212
Start the PerfMon Agent��������������������������������������������������������������������������������������������������������������������� 213
Non-GUI Mode������������������������������������������������������������������������������������������������������������������������������������ 218
Conclusion�������������������������������������������������������������������������������������������������������������������� 219
■
■Chapter 10: JMeter Recipes������������������������������������������������������������������������������ 221
JDBC Performance Testing������������������������������������������������������������������������������������������� 221
Install MySQL�������������������������������������������������������������������������������������������������������������������������������������� 221
Install JDBC Driver������������������������������������������������������������������������������������������������������������������������������ 224
JDBC Test Plan������������������������������������������������������������������������������������������������������������������������������������ 224
xii
■ Contents
Conclusion�������������������������������������������������������������������������������������������������������������������� 242
■
■Chapter 11: Case Study: Digital Toys Inc.���������������������������������������������������������� 243
The Need for Speed������������������������������������������������������������������������������������������������������ 243
Addressing the Problem����������������������������������������������������������������������������������������������� 244
Performance Goals����������������������������������������������������������������������������������������������������������������������������� 244
Performance Test Specification���������������������������������������������������������������������������������������������������������� 244
Tool Selection������������������������������������������������������������������������������������������������������������������������������������� 247
Test Environment�������������������������������������������������������������������������������������������������������������������������������� 247
Test Data Preparation������������������������������������������������������������������������������������������������������������������������� 248
User Load Pattern������������������������������������������������������������������������������������������������������������������������������� 248
Application Build��������������������������������������������������������������������������������������������������������������������������������� 249
xiii
■ Contents
Outcome����������������������������������������������������������������������������������������������������������������������� 301
Conclusion�������������������������������������������������������������������������������������������������������������������� 302
■
■Chapter 12: Performance Dashboard���������������������������������������������������������������� 303
APDEX��������������������������������������������������������������������������������������������������������������������������� 303
Configuration���������������������������������������������������������������������������������������������������������������� 303
JMeter Properties������������������������������������������������������������������������������������������������������������������������������� 304
APDEX������������������������������������������������������������������������������������������������������������������������������������������������� 304
Global Graph Properties���������������������������������������������������������������������������������������������������������������������� 304
Specific Graph Properties������������������������������������������������������������������������������������������������������������������� 305
Windows����������������������������������������������������������������������������������������������������������������������� 318
Download JDK������������������������������������������������������������������������������������������������������������������������������������ 318
Install JDK������������������������������������������������������������������������������������������������������������������������������������������� 319
Set Up the Environment Variable�������������������������������������������������������������������������������������������������������� 320
Download JMeter������������������������������������������������������������������������������������������������������������������������������� 321
Set Up JMeter������������������������������������������������������������������������������������������������������������������������������������� 321
Linux����������������������������������������������������������������������������������������������������������������������������� 322
Install JDK������������������������������������������������������������������������������������������������������������������������������������������� 322
Set Up the Environment Variable�������������������������������������������������������������������������������������������������������� 323
Download JMeter������������������������������������������������������������������������������������������������������������������������������� 323
Set Up JMeter������������������������������������������������������������������������������������������������������������������������������������� 324
xiv
■ Contents
■
■Chapter 14: Appendix B: Setting Up Digital Toys Inc.���������������������������������������� 327
Running Digital Toys Web Application�������������������������������������������������������������������������� 327
Start the Web Application������������������������������������������������������������������������������������������������������������������� 327
Start with URL Rewriting Enabled������������������������������������������������������������������������������������������������������ 330
Clean Up��������������������������������������������������������������������������������������������������������������������������������������������� 331
Index��������������������������������������������������������������������������������������������������������������������� 333
xv
About the Authors
Jagdeep Jain has more than a decade of experience in software quality assurance
and testing. He holds a degree in Computer Science and Engineering. He is a
firm believer and advocate of test automation, and he has used Apache JMeter
extensively.
xvii
About the Technical Reviewer
Nitesh Kumar Jain has over a decade of experience in the software testing world.
He has an M.Tech in Information technology from IIITM Gwalior and a B.E. in
Computer Science and Engineering. He is a keen technology learner with an
“let’s automate everything” attitude. He is also an ISTQB certified test manager,
technical test analyst, test analyst, and Agile test engineer and loves to make Java-
Swing based tools that can help with software testing. He also spent five years on
performance testing and test automation.
xix
Acknowledgments
We want to thank the following people who have helped us make sure that the book is useful by providing
timely feedback on our chapters, testing JMeter scripts, and finding bugs in our sample web application.
Without them, it would have been tough to create a good quality book.
Ai Yu, Alap Shah, Amit Devgan, Anand Sinha, Anil Ramesh Malleboyina, Anil Wadghule, Beejal Vibhakar,
Belal Ansari, Bhushan Gupta, Chakradhar Kommera, Charan Das Thota, David Livingstone Gangarapu,
Deepa Mahendraker, Dheeraj Sah, Etender Naini, Ganesh Somaka, Gomtesh Gandhi, Govardhan Aliseri,
Haridev Vengateri, Harshad Savot, Harshvardhan Vipat, Hemanth Presingu, Mangesh Lunawat, Manjula
Gundugollu, Manjula Kavadi, Manohar Gone, Nikhil Agrawal, Nitish Shirsath, Pankaj Saraf, Piyush Singh,
Prashanth Abbagani, Prasoon Kumar, Raj Gopal Marripalli, Rama Gangadhar Mekala, Ram Katru, Roshan
Iqbal, Ruth Rajitha Gangarapu, Sanjeev Kumar, Satish Salandri, Satyapal Reddy Panyala, Sharon Annese,
Shravan Goli, Shyam Palleti, Shyam Palreddy, Sridhar Throvagunta, Srikanth Ganapavarapu, Srinivas
Nagandla, Srinivas Reddy Gaddam, Sudeep Tripathy, Suneeta Donepudi, Sunil Kumar, Sunil Potti, Swamy
Das, Tapan Upadhyay, Tarak Joshi, Vidhut Singh, Vijay Pasupuleti, Yogesh Sharma and Yogesh Yadhav.
We are very thankful to the editorial team at Apress and the technical reviewer for having various
checkpoints in place and providing us with useful feedback in a timely manner, all of which have made this
book more useful for readers.
xxi
Introduction
This book is intended to get beginners up and running with performance testing using JMeter. This book
provides step-by-step guidance and covers advanced topics for the experienced engineer. Each chapter is
clearly marked with the topics it covers, thereby allowing the reader to skip chapters if appropriate.
Chapter 1 is the foundation of the book where we discuss why performance testing is needed and why
we should user JMeter.
Chapter 2 is general-purpose chapter that covers the performance testing methodology.
Chapters 3 through 5 cover specific topics in JMeter (test plan, thread group, pre-processors, controller,
timers, sampler, assertions, listeners, post-processors, properties, and variables). By going through these
chapters, you will gain an understanding on how to user JMeter for your performance needs.
Chapters 6 through 10 deal with distributed testing, a few advance concepts of JMeter, and
troubleshooting tips that will be useful in some projects.
Chapter 11 contains the case study of a sample web application called Digital Toys Inc. This chapter
contains everything that a performance testing engineer needs to start performance testing a project.
Chapter 12 shows you how to generate a performance dashboard while executing test scripts.
Chapters 13 and 14 help in setting up JMeter and sample web applications to run the test scripts.
Architects, engineers, and quality assurance professionals will greatly benefit by reading this book.
Project managers or other non-technical team members may want to glance through the book and read
Chapter 2, “Performance Testing Primer,” to gain some understanding on performance testing in general.
We have developed an e-commerce web application for a hypothetical company called Digital Toys Inc., for
the express purpose of illustrating the example test scripts in this book. Chapter 14 explains how to set up
this sample application.
Test scripts developed in this book are hosted on GitHub. Any source code or other supplementary material
referenced by the authors in this book is available to readers on GitHub via the book’s product page, located at
www.apress.com/978-1-4842-2960-6. For more detailed information, visit http://www.apress.com/source-code.
For any quires or valuable feedback, feel free to get in touch with authors over e-mail:
Sai Matam at [email protected].
Jagdeep Jain at [email protected].
xxiii
CHAPTER 1
Foundation
In many companies, performance testing is not a priority until it becomes critical. The engineering team
is then asked to complete performance testing in an extremely short time. Most of us are familiar with this
situation and can relate to it. The engineering team needs to come up to speed with performance testing in
general and with performance testing tools in a very short time.
In spite of realizing how critical performance testing is, companies often don’t have an adequate budget
for the needed commercial performance testing tools. Apache JMeter (hereinafter referred to as “JMeter”)
is the leading tool, and thankfully it is open source and thus is free.
While there is plenty of reference material on the Internet, there is no comprehensive guide to take you
through all the steps of creating, running, and interpreting the results of a performance test using JMeter.
This book aims to address this need.
This book discusses the basics and presents a framework for performance testing. You will be able
to create a performance test plan that is based on the requirements. This book follows a step-by-step
approach and guides you through the installation, configuration, test plan creation, execution, and result
interpretation using JMeter.
Chadburn, Matt, Lahav, Gadi; “A Faster FT.com.” Engine Room, Blog by the Financial Times Technology Department,
1
Why JMeter?
JMeter is an industrial-strength performance testing tool. It is a top-level Apache open source project.
But being free is not the only reason for its popularity. It’s a very capable tool. This mature tool has been
continuously revised since its inception in 2001.
The commercial tools may have fancier user interfaces or better-looking reports, but JMeter can
be configured to provide the same capabilities. JMeter can be run in “distributed mode” in the cloud,
generating the load of thousands of users. JMeter comes with an Apache License, which does not have any
restrictions on usage, distribution, or modification.
JMeter has a standard format for writing the performance test. Most of the commercial tools support
importing/exporting to the JMX (the JMeter test file format).
2
CHAPTER 3
This chapter discusses the various components of JMeter and helps you develop the first JMeter test script.
You will find out about the various ways (GUI/non-GUI) of running and stopping/shutting down JMeter test
scripts in standalone test execution and server mode of test execution.
At the end of this chapter, you will have a good idea of the various components of JMeter and be able to
write a simple JMeter test script, as well as start/stop/shut down tests from GUI and non-GUI modes.
Before starting with the JMeter test script development, let’s walk through the components of a test plan.
A JMeter test script consists of hierarchical and ordered components organized in the form of a tree.
Each of these components has properties that can be configured in the following ways:
• By jmeter.properties file
• By using command-line parameters
• By editing the .jmx file directly using a text editor
• By using the GUI
• By using values extracted from the responses received to sampler requests
Test Plan
The test plan is the top-most element and is the root of the tree. For a test plan, the name, description, and
user variables can be configured.
Thread Group
Every test has one or more thread groups. A thread group is a child element of a test plan. Each thread group
represents a use-case. As you will see later in the book, a thread group can be configured with the number of
threads, ramp-up time, and other useful properties that allow you to control its behavior.
Controller
Each thread group has one or more controller elements. Logical controllers decide the flow of execution.
They determine the next Sampler to execute. JMeter comes with many built-in logical controllers that
provide precise control flow. For example, the If controller and Switch controller provide branching; the
ForEach, While, and For provide iteration flow. There is a controller for every programming construct.
A custom controller, if needed, could be developed using the plugin API mechanism provided by JMeter.
Sampler
Sampler is a child element of a thread group or a controller. It sends requests to the server. For every
protocol, we need a separate sampler. Out of the box, JMeter comes with many samplers. For example,
to send a HTTP request, you use a HTTP Request Sampler. Custom samplers can be developed using the
JMeter plugin mechanism.
Listener
Listeners listen to the responses from the server and assemble and aggregate the performance metrics.
They are used to display graphs. We need at least one listener per test script so that we can interpret and
understand the results of the performance test.
Timer
A timer introduces a delay in the flow. Delay is needed between sampler requests for the following reasons:
• To simulate the time that the user takes to perform the next action on the web page
• To simulate a realistic load distribution on the server
Add timers as child elements of samplers or logic controller that need the delay.
Assertions
Assertions are used to verify that the server responses are as expected. Assertions test various status codes,
and then pause, alert, or log bad request/responses. It is important to ensure that the server is not returning
any error codes during the execution.
Adding an assertion as a child of the sampler restricts it to a single sampler. Otherwise, assertions will
apply to all samplers that are in scope.
Add an Assertion Results Listener to the thread group to view the assertion results. Failed assertions will
also be displayed in the View Results Tree and the View Results in Table Listeners, and will count toward the
error percentage, for example, in the Aggregate Reports and Summary Reports.
Config Element
Configuration elements are placeholders for properties, including user-defined properties and variables.
For example, the HTTP Cookie Manager is a configuration element. Configuration elements can be scoped
out with a nesting level.
14
Chapter 3 ■ Your First JMeter Test
Pre-Processors
Pre-processors take the request and modify it (substitution, enhancement, dereferencing variables, etc.)
before the sampler sends it to the server.
Post-Processors
Post-processors process the response from the server. They are used to process the server response and
modify the component settings or to update variables.
15
Chapter 3 ■ Your First JMeter Test
JMeter allows the elements to be nested. For example, a listener, a timer, and a sampler can be nested
under a logical controller. In this case, when the logical controller is being executed, the order of execution of
its child nodes would be the timer, the sampler, then the listener.
Figure 3-2 shows the order of execution in the test plan.
As you can see in the JMeter test plan, the components are not in sequence.
However, JMeter will rearrange them according to the Order of Execution diagram shown in Figure 3-1.
Note that the CSV Data Set Config is nested under the transaction controller. The child elements nested under
the transaction controller would again follow the Order of Execution diagram and get sequenced.
For the given test plan, the execution order will be:
1.
BeanShell Pre-processor
2.
Constant Timer
3.
Constant Throughput Timer
4.
Transaction Controller
5.
CSV Data Set Config
6.
HTTP Request
7.
BeanShell PostProcessor
8.
Aggregate Report
■■Note All the examples mentioned in this book have been coded against a sample web application called
Digital Toys Inc. Refer to Chapter 14 for setup instructions.
16
Chapter 3 ■ Your First JMeter Test
1
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_03/FirstTestPlan.jmx
17
Chapter 3 ■ Your First JMeter Test
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler and add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as
/dt. Uncheck Follow Redirects (see Figure 3-4).
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions and add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200 (see Figure 3-5).
Figure 3-5. Assertions
18
Chapter 3 ■ Your First JMeter Test
6.
Click on Thread Group and go to Edit ➤ Add ➤ Listener and add View Results
Tree (see Figure 3-6).
7.
Save the test plan.
8.
Go to Run ➤ Start to run the test (on Mac OSX, type CMD+R).
9.
Verify the responses in the View Results Tree (see Figure 3-7).
19
Chapter 3 ■ Your First JMeter Test
20
Chapter 3 ■ Your First JMeter Test
Navigate to each response under the View Results Tree and verify the response and response time
(Load Time). Calculate the average response time as the sum of the response time of all threads/number of
threads.
GUI Mode
JMeter GUI mode provides several options to start/stop test(s) (see Figure 3-9).
21
Chapter 3 ■ Your First JMeter Test
■■Note Use the GUI to create and debug the tests scripts. Use the non-GUI mode to execute the test and
collect the results.
Non-GUI Mode
GUI mode is not desirable because:
• It consumes a large amount of resources, thus interfering with the test results
• It may not be available in some environments (such as a remote shell)
To avoid these issues, use the non-GUI mode.
To see the command line options provided by JMeter, issue the following command in the CMD prompt.
jmeter --help
C:\apache-jmeter-3.0\bin>jmeter --help
Writing log file to: C:\apache-jmeter-3.0\bin\jmeter.log
_ ____ _ ____ _ _ _____ _ __ __ _____ _____ _____ ____
/ \ | _ \ / \ / ___| | | | ____| | | \/ | ____|_ _| ____| _ \
/ _ \ | |_) / _ \| | | |_| | _| _ | | |\/| | _| | | | _| | |_) |
/ ___ \| __/ ___ \ |___| _ | |___ | |_| | | | | |___ | | | |___| _ <
/_/ \_\_| /_/ \_\____|_| |_|_____| \___/|_| |_|_____| |_| |_____|_| \_\ 3.0 r1743807
To list all command line options, open a command prompt and type:
jmeter.bat(Windows)/jmeter.sh(Linux) -?
--------------------------------------------------
To run Apache JMeter in GUI mode, open a command prompt and type:
--------------------------------------------------
22
Chapter 3 ■ Your First JMeter Test
--------------------------------------------------
--------------------------------------------------
To generate a Report from existing CSV file:
Open a command prompt (or Unix shell) and type:
--------------------------------------------------
---------------------------------------------------
jmeter-server.bat(Windows)/jmeter-server(Linux)
---------------------------------------------------
C:\apache-jmeter-3.0\bin>
2
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_03/FirstTestPlan.jmx
23
Chapter 3 ■ Your First JMeter Test
C:\>jmeter-server
... Trying JMETER_HOME=..
Found ApacheJMeter_core.jar
Writing log file to: C:\apache-jmeter-3.0\bin\jmeter-server.log
Created remote object: UnicastServerRef [liveRef: [endpoint:[172.17.65.111:61425]
(local),objID:[-10c0a943:15c299a388a:-7
fff, -3710696168706880958]]]
Stop/Shutdown JMeter
To stop JMeter test execution, issue the following command in the CMD prompt. Once the command
executes, it sends a stop signal to the JMeter test. The response message in the CMD prompt should read
StopTestNow request to port 4445.
C:\apache-jmeter-3.0\bin>stoptest.cmd
Sending StopTestNow request to port 4445
To shut down JMeter, issue the following command in the CMD prompt. Once the command executes,
it will send a shutdown signal to the JMeter test. The response message in the CMD prompt should read
Shutdown request to port 4445.
C:\apache-jmeter-3.0\bin>shutdown.cmd
Sending Shutdown request to port 4445
Conclusion
In this chapter, you learned about the components of a JMeter test and wrote a simple JMeter test. You also
learned how to start/stop/shut down JMeter test execution via GUI mode and from the command prompt.
In the next chapter, you will learn to record user actions and create JMeter test scripts by using HTTP(s) Test
Script Recorder.
24
CHAPTER 4
This chapter discusses how to record a JMeter test script by using HTTP(S) Test Script Recorder. We cover
the WorkBench and Recording Controller, how to configure a proxy port for recording HTTP(S) calls, and
inclusion and exclusion of specific URL patterns. You will also see how to record an example using the
Digital Toys Inc. web application.
At the end of this chapter, you will have a good idea of recording user actions via a browser and will
be able to develop a simple JMeter test script. Those who are already familiar with the HTTP(S) Test Script
Recorder can proceed to the next chapter.
Before starting with the HTTP(S) Test Script Recorder, you need to make sure that JMeter understands
browser actions. You need to configure the browser and use JMeter as a proxy server.
Once you complete the configuration, you can use the browser and perform the use-case specific steps
on a browser. JMeter, being in the middle, can intercept the requests from the browser, record them, and
forward them to the server. Similarly, JMeter can record the web application responses before forwarding
them back to the browser. See Figure 4-1.
JMeter WorkBench
JMeter’s WorkBench provides a temporary workspace to store test elements, including a thread group. When
the JMeter GUI starts, it is pre-populated with an empty test plan and an empty WorkBench. When JMeter
is configured as a proxy, it can record the browser activity in the WorkBench. Users can then copy/paste
recorded requests from the WorkBench into the test plan.
Test elements in the WorkBench are considered a work-in-progress. They are not saved with the test
plan unless you check the Save WorkBench check-box. See Figure 4-2.
Apart from the test elements, it can contain non-test elements like a HTTP(s) Test Script Recorder.
See Figure 4-3.
26
Chapter 4 ■ JMeter Test Script Recorder
WorkBench provides us with a few configuration options for recording test scripts, such as global
settings, test plan content, URL patterns to include, URL patterns to exclude, and notify child listeners of
filtered samplers. See Figure 4-4.
Figure 4-4. WorkBench
In Global Settings, the Port configuration is used to configure JMeter to listen on a specified port.
Test plan content allows you to specify the controller where the proxy will store the generated samples.
It is set to Recording Controller by default.
The URL Pattern to Include option allows you to add a regular expression that specifies the URLs to
include. For example, use the regular expression .\/product\/. to specify a URL containing the product.
The URL Patterns to Exclude option allows you to add a regular expression to specify the URLs to
exclude. For example, you can use the regular expression .\.(css|js). to indicate that you don’t want
CSS or js.
Selecting the Notify Child Listeners of Filtered Samplers check box causes the child Listener (for example,
the View Results Tree) not to see these requests.
27
Chapter 4 ■ JMeter Test Script Recorder
JMeter is now the proxy between the Firefox browser and the web server.
28
Chapter 4 ■ JMeter Test Script Recorder
Recording Example
Using the Digital Toys Inc. web application, we will now place an order. Because JMeter has been set up as
the proxy, you can record all the user interactions on the browser.
Follow these steps.
1.
Sign in (user: [email protected], password: user1).
2.
Go to Check Detail ➤ Add To Cart ➤ Checkout ➤ Add Billing/Shipping Address ➤
Add Credit Card ➤ Place Order ➤ Sign Out.
Let’s illustrate the process of developing a test script by recording the user actions.
Follow these steps or download FirstRecordingTestPlan.jmx1:
1.
Create a test plan and give it a meaningful name, such as First Recording Test.
2.
Click on WorkBench and go to Edit ➤ Add ➤ Non-Test Elements. Then add
HTTP(S) Script Test Recorder. In Global Settings, configure Port as 7070. Select
Target Controller as WorkBench > HTTP(S) Test Script Recorder.
3.
Click on the Start button. JMeter will show a Root CA Certificate dialog box. Click OK.
4.
Perform the use-case actions in the browser; they will be shown as in Figure 4-6.
1
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_04/FirstRecordingTestPlan.jmx
29
Chapter 4 ■ JMeter Test Script Recorder
5.
Click on the Stop button.
6.
After recording, you will notice requests for .js, .css, and other resources that
are not needed. You can exclude these requests by specifying Exclude Regular
Expression. Click on Add Suggested Excludes, and this action will add a sample
expression. Modify this expression, as shown in Figure 4-7.
.*\.(bmp|css|js|gif|ico|jpe?g|png|swf|woff|woff2|ttf).*
■■Note We have excluded .bmp, .css, .js, .gif, .ico, .jpeg, .png, .swf, .woff, .woff2, and .ttf
requests. This is because our focus was to test the performance of the dynamic responses from the server.
7.
Clear the previous recording.
You will now re-record the use-case without the unwanted requests.
1.
Click on the Start button. JMeter will show a dialog box. Click OK.
2.
Perform the use-case actions in the browser.
3.
You will now see that the recorded calls have been filtered for unwanted
resources. See Figure 4-8.
30
Chapter 4 ■ JMeter Test Script Recorder
4.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add a thread group.
5.
Select all recorded browser actions from WorkBench and then drag and add
them as child elements of the thread group. The result will look as shown in
Figure 4-9.
31
Chapter 4 ■ JMeter Test Script Recorder
After the test executes, open the browser, navigate to the Digital Toys Inc. web application, log in with
the [email protected] username and user1 password, then navigate to Order History and check if the order
is present. You should see two orders—the first order was created while recording the test and the second
order was created due to the test execution. See Figure 4-11.
33
Chapter 4 ■ JMeter Test Script Recorder
■■Note We excluded .js, .css, .ico, .ttf, .woff, etc. requests, which are basically browser-based calls instead
of server calls. This is because the focus here is to test the performance of dynamic responses from the server.
Conclusion
In this chapter, you learned to configure JMeter as a proxy and use the HTTP(S) Test Script Recorder. You
used regular expressions to include/exclude specific URLs in your test script and successfully developed
a JMeter test script. In the next chapter, you will learn about the test plan and its components and explore
various options for each of those components.
34
CHAPTER 5
This chapter discusses various components of a typical JMeter test plan. Readers are required to read
through this chapter carefully and understand various configuration points of each components. We cover
configurations and use of test plans, thread groups, pre-processors, logic controllers, timers, samplers,
assertions, post-processors, properties, variables, and user defined variables.
By the end of this chapter, you will have a good idea of the various components of a typical test plan and
will have a good understanding of the configurations and uses of these components. You will also be able to
develop a standard JMeter test script. Those who are already familiar with any of these components can skip
the appropriate sections and move forward to the next section.
Test Plan
The test plan is the root element of the JMeter test. It is a container that holds JMeter components like the
thread group, logic controller, sampler, listener, timer, assertion, and config element. A test plan (see Figure 5-1)
consists of one or more thread groups.
Configuration
Figure 5-1 shows the configuration of a test plan. The configuration points are described next.
• User Defined Variables: These are defined by using name/value pair(s). Click the
Add button to create a new name/value pair. If you have more than one, create a list
of name/value pairs, one per line, in a text file. Select all of them and then click on
Add Clipboard to add all of them at the same time. Select one or more and click on
the Delete button to delete. Use the Up and Down buttons to change the order.
• Run Thread Groups Consecutively (i.e. Run Groups One at a Time): A test plan
can have more than one thread group. If this checkbox is enabled, then the thread
groups are executed one after the other. If this checkbox is not enabled (the default),
the thread groups are executed in parallel.
• Run tearDown Thread Groups After Shutdown of Main Threads: If this checkbox
is selected, then tearDown thread groups executes after the test has finished
executing its regular thread group. It is used for doing things post test execution for
reporting purposes or performing cleanup operations.
36
Chapter 5 ■ JMeter Test Plan Components
• Functional Test Mode (i.e. Save Response Data and Sampler Data): If this
checkbox is selected, then sampler requests and response data are saved in the
listeners. This allows you to verify that the test is working as expected. The use of this
feature is not recommended.
• Add Directory or JAR to Classpath: You can add a folder or a JAR file to the
classpath and JMeter can load these classes. For consistent behavior, restart JMeter
after modifying this.
We explore serial execution of thread groups, parallel execution of thread groups, and user defined
variables in the following sections.
1
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/test-plan/
SerialExecutionOfThreadGroupTestPlan.jmx
37
Chapter 5 ■ JMeter Test Plan Components
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure the Name as Thread Group A and Loop Count as 4 (see Figure 5-3).
3.
Click on Thread Group A and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Alpha, Server Name or IP as localhost, Port Number as
8080, and Path as /jmeter/alpha.
4.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure the Name as Thread Group B and Loop Count as 4.
5.
Click on Simple Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Bravo, Path as /jmeter/bravo, and Method as GET.
6.
Click on Test Plan and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
7.
Save the test plan.
8.
Run the test.
38
Chapter 5 ■ JMeter Test Plan Components
2
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/test-plan/
ParallelExecutionOfThreadGroupTestPlan.jmx
39
Chapter 5 ■ JMeter Test Plan Components
2.
Click on the test plan and uncheck the Run Thread Groups Consecutively
checkbox (see Figure 5-5).
3.
Run the test (see Figure 5-6).
40
Chapter 5 ■ JMeter Test Plan Components
■■Tip Pay attention to the Run Thread Groups Consecutively (i.e. Run Groups One at a Time) checkbox.
■■Note Last section of this chapter “Properties and Variables” describes UDV with an example.
41
Chapter 5 ■ JMeter Test Plan Components
Thread Group
The Thread Group element is the starting point of execution. All elements can be the child elements of a
test plan or a thread group (see Figure 5-7), except for controllers and samplers, which can only be the child
elements of a thread group.
The thread group is simulating the load generated by users performing a use-case. A test plan can have
multiple thread groups, thus simulating multiple use-cases.
Although uncommon, data can be exchanged between thread groups.
The Number of Threads (Users) option is used to specify the number of users accessing the web
application. When the test starts initially, threads are spawned based on the configuration option called
Ramp-Up Period (in Seconds).
You can also schedule tests to run at a particular time.
When a test fails, the behavior to continue or to stop is configurable (see Figure 5-8).
42
Chapter 5 ■ JMeter Test Plan Components
Thread Properties
The Thread Properties option (see Figure 5-9) gives you the flexibility to simulate a realistic load.
43
Chapter 5 ■ JMeter Test Plan Components
• Number of Threads (Users): This is the number of users we want to use for load
testing a web application.
• Ramp-Up Period (in Seconds): This is the time after which all threads will be active.
Assume that you want to start 10 threads, with a thread starting every second, then configure the
thread group with Number of Threads (users) as 10 and RampUp Period (in Seconds) as 10. With this
configuration, 10 threads will start in 10 seconds and all threads will be active after 10 seconds.
Let’s see how to use Number of Threads (Users) and Ramp-Up Period (in Seconds) using the following
example.
Follow these steps or download ThreadGroupTestPlan.jmx.
1.
Create a test plan and give it a meaningful name, such as Thread Group Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure Number of Threads (users) as 10 and Ramp-Up Period (in seconds)
as 10 (see Figure 5-10).
44
Chapter 5 ■ JMeter Test Plan Components
3.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as /dt.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
5.
Save the test plan.
6.
Run the test.
The results will be similar to those shown in Figures 5-11 and 5-12.
45
Chapter 5 ■ JMeter Test Plan Components
7.
Click on each of the responses and look for Sample Start. This will show you
when the thread started. You will find that each thread was started after a gap
of 1 second.
• Loop Count: This option controls the number of iterations that the thread
group runs.
Let’s see how to use Loop Count using the following example.
Follow these steps or download LoopedThreadGroupTestPlan.jmx.3
1.
Create a test plan and give it a meaningful name, such as Looped Thread Group Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure Number of Threads (users) as 1, Ramp-Up Period (in seconds) as 1,
and Loop Count as 2 (see Figure 5-13).
3.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as /dt.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
5.
Save the test plan.
3
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/thread-group/
LoopedThreadGroupTestPlan.jmx
46
Chapter 5 ■ JMeter Test Plan Components
6.
Run the test. The results are shown in Figure 5-14.
7.
Since we have configured Loop Count as 2, two responses are captured inside
View Results Tree.
• Forever: By selecting this checkbox, we are telling JMeter that the execution should
iterate until the user clicks the Stop or Shutdown buttons.
Let’s see how to use Forever option using the following example.
Follow these steps or download ForeverRunningThreadGroupTestPlan.jmx.4
1.
Create a test plan and give it a meaningful name, such as Forever Running
Thread Group Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure Number of Threads (users) as 1, Ramp-Up Period (in seconds) as 1
and click the Forever checkbox (see Figure 5-15).
4
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/thread-group/
ForeverRunningThreadGroupTestPlan.jmx
47
Chapter 5 ■ JMeter Test Plan Components
3.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as /dt.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
5.
Save the test plan.
6.
Run the test.
7.
The test will never end, with responses being added to the View Results Tree
Listener.
8.
Click on the Stop button to stop the test immediately or click on the Shutdown
button to terminate the test gracefully.
48
Chapter 5 ■ JMeter Test Plan Components
Scheduler
The other properties of the thread group are Scheduler and Delayed Thread Creation until Needed
(see Figure 5-16).
Figure 5-16. Scheduler
Web site traffic load patterns vary based on the time of day. This can be simulated by configuring the
scheduler to run the test at a particular time.
Let’s see this in the following example.
Follow these steps or download ScheduledThreadGroupTestPlan.jmx.5
1.
Create a test plan and give it a meaningful name, such as Scheduled Thread
Group Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure Number of Threads (users) as 1, Ramp-Up Period (in seconds) as 1,
and then click the Forever checkbox (see Figure 5-17).
3.
Click on the Scheduler checkbox. Let’s say the system time is 07:18:10 and you
want the test to run 5 minutes from now. Configure the Start Time to 07:23:10
and End Time to 07:23:11. Here, you are telling JMeter to run the test 5 minutes
from now and to run it for .01 seconds (see Figure 5-17).
5
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/thread-group/
ScheduledThreadGroupTestPlan.jmx
49
Chapter 5 ■ JMeter Test Plan Components
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as /dt.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
6.
Save the test plan.
7.
Run the test. The test will not run immediately, as execution was scheduled to
start after 5 minutes. Wait for 5 minutes and you will see responses under the
View Results Tree. Look at the Sampler Start time; it will show the configured
value (see Figure 5-18).
50
Chapter 5 ■ JMeter Test Plan Components
51
Chapter 5 ■ JMeter Test Plan Components
3.
Save the test plan.
4.
Click on the Start button. The test will not start immediately, but will start
automatically after 10 seconds and end after 2 seconds (see Figure 5-20).
52
Chapter 5 ■ JMeter Test Plan Components
2.
Run the test.
3.
Verify the results of the test script execution by logging into the Digital Toys Inc.
web application as [email protected]/user100. Navigate to Order History. You
should now see the recently placed order in the Order History for this user.
Controller
Controllers determine the sequence in which the samplers are processed. These are analogous to the control
flow constructs in common programming languages. The names of the controllers are indicative of their
function.
Logical controllers can be categorized as follows:
1.
Controllers for grouping
a. Simple Controller
b. Transaction Controller
2.
Controllers for looping
a. Loop Controller
b. While Controller
c. ForEach Controller
3.
Controllers for decision making
a. If Controller
b. Switch Controller
c. Once Only Controller
d. Interleave Controller
e. Random Controller
f. Random Order Controller
63
Chapter 5 ■ JMeter Test Plan Components
4.
Controllers for modularity
a. Module Controller
b. Include Controller
5.
Controllers for recording
a. Recording Controller
6.
Other controllers
a. Critical Section Controller
b. Throughput Controller
c. Runtime Controller
JMeter can be extended by writing custom controllers.
Simple Controller
The Simple Controller provides no functionality beyond that of grouping, primarily to organize samplers and
other logic controllers.
■■Note The Simple Controller is not often used. Instead, consider using the transaction controller, which is
discussed later in the chapter.
12
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
SimpleControllerTestPlan.jmx
64
Chapter 5 ■ JMeter Test Plan Components
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-33.
Transaction Controller
The Transaction Controller provides the functionality of grouping elements together, similar to Simple
Controller. In addition to that, it generates an additional entry in the listener that measures the overall time
taken to perform the nested test elements.
Let’s look at an example that illustrates the use of a Transaction Controller.
Follow these steps or download TransactionControllerTestPlan.jmx.13
1.
Create a test plan and give it a meaningful name, such as Transaction
Controller Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP as localhost and Port Number
as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller and add
Transaction Controller. Do not select any of the checkboxes.
5.
Click on Transaction Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP
Request. Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
6.
Click on Transaction Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP
Request. Configure Name as Bravo, Path as /jmeter/bravo, and Method as GET.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
13
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
TransactionControllerTestPlan.jmx
65
Chapter 5 ■ JMeter Test Plan Components
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-34.
These results indicate that there is a new entry in the results table that has the combined aggregate
values of the sample time (ms), latency, bytes, and connect time.
The Transaction Controller can function in Parent Mode. This can be enabled using a checkbox as
shown in Figure 5-35 and then the additional sample is added as a parent of the nested samples.
The Transaction Controller is considered successful only if all the samplers under it are successful.
In the Parent Mode, the individual samples can still appear in the View Results Tree, but no longer
appear as separate entries in View Results in Table or in other listeners. Also, the sub-samples do not appear
in CSV log files, but they can be saved to XML files (see Figure 5-36).
66
Chapter 5 ■ JMeter Test Plan Components
By default, Transaction Controller does not include the time taken by timers and pre-processors.
However, it can be configured to include the timers by enabling a checkbox, as shown.
Follow these steps or download TransactionControllerConstantTimerTestPlan.jmx.14
1.
Open TransactionControllerTestPlan.jmx.
2.
Go to File ➤ Save Test Plan as and type in a filename, such as
TransactionControllerConstantTimerTestPlan.jmx.
3.
Give the test plan a meaningful name, such as Transaction Controller And
Constant Timer Test.
4.
Click on Transaction Controller and go to Edit ➤ Add ➤ Timer. Add Constant
Timer. Configure Thread Delay (in Milliseconds) to 1000 (see Figure 5-37).
14
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
TransactionControllerConstantTimerTestPlan.jmx
67
Chapter 5 ■ JMeter Test Plan Components
5.
Save the test plan.
6.
Run the test.
The results will be similar to those shown in Figure 5-38.
The result indicates that the aggregate is one second more than the sum of the HTTP Request Sampler.
This is because the time taken by the timer has been added to the aggregate.
Loop Controller
The Loop Controller provides a looping mechanism. It can repeat the execution of its nested elements a
specified number of times. It also has a checkbox to configure it to loop forever.
Let’s look at an example that illustrates the use of a Loop Controller.
Follow these steps or download LoopControllerTestPlan.jmx.15
1.
Create a test plan and give it a meaningful name, such as Loop Controller Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP as localhost and Port Number
as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add Loop
Controller. Configure the Loop Count as 4 (see Figure 5-39).
15
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
LoopControllerTestPlan.jmx
68
Chapter 5 ■ JMeter Test Plan Components
6.
Click on Loop Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Bravo, Path as /jmeter/bravo, and Method as GET.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in
Table.
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-40.
69
Chapter 5 ■ JMeter Test Plan Components
As you can see in the results, alpha was called once followed by four requests to bravo.
The Loop Controller can be configured to loop indefinitely by enabling the Forever checkbox. This gets
enabled even if you enter any negative number for Loop Count.
If you run the test with the Forever checkbox enabled, you need to click on the Shutdown button and
terminate the test gracefully. Clicking on the Stop button terminates the threads abruptly, and you may see
some errors in the requests.
Runtime Controller
The Runtime Controller controls the duration for which its child elements are run.
A Runtime Controller executes its child elements in its hierarchy for the specified duration. At the end of
the nested elements, it loops through again. Using the same logic, if the specified time runs out, the Runtime
Controller stops execution even if it has executed only a part of the nested elements. The currently executing
element is allowed to complete, but the newer elements are not executed once the specified time is over.
The configuration is very simple. You just have to enter the number of milliseconds for which the child
elements should be run. If the duration field is 0 or a negative number, all the child elements are completely
skipped.
This also works as a looping mechanism; the only difference being that instead of the specified number
of iterations, the child elements are looped for a specified elapsed time.
Let’s look at an example that illustrates the use of a Runtime Controller.
Follow these steps or download RuntimeControllerTestPlan.jmx.16
1.
Create a test plan and give it a meaningful name, such as Runtime Controller Test
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP to localhost and Port Number
to 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add Runtime
Controller. Configure Runtime (seconds) to 10 (see Figure 5-41).
16
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
RuntimeControllerTestPlan.jmx
70
Chapter 5 ■ JMeter Test Plan Components
5.
Click on Runtime Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP
Request. Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
6.
Click on Runtime Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP
Request. Configure Name as Bravo, Path as /jmeter/bravo, and Method as GET.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-42.
71
Chapter 5 ■ JMeter Test Plan Components
Observe that the time difference between the last and the first sample is 9.182 seconds, which is
approximately 10 seconds. This is working as configured. See Table 5-1 for more detail.
Throughput Controller
The Throughput Controller controls the number of executions of its child elements. This is a misnomer, as it
does not control the throughput; use the Constant Throughput Timer for that.
You can configure this in two modes:
• Number of Executions: The child elements are executed until the specified count is
reached and the subsequent executions are skipped. To configure this, choose Total
Executions and specify a value for Throughput.
• Percentage of Executions: The concept is the same except that the number
of executions of the child elements is restricted by the percentage configured.
To configure this, choose Percent Executions and specify a value for Throughput
(omit the % sign).
Both of these modes limit the number of executions of the controller. These limits apply collectively to
all the threads in the thread group. These limits apply on a per thread basis when the Per User checkbox is
enabled.
The following example demonstrates this concept. We will configure the Throughput Controller in Total
Executions mode to execute based on a count specified.
Follow these steps or download ThroughputControllerTestPlan.jmx.17
1.
Create a test plan and give it a meaningful name, such as Throughput
Controller Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure Loop Count as 10.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP as localhost and Port Number
as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add
Throughput Controller. Configure Throughput as 3, and then select
Total Executions from the drop-down (see Figure 5-43).
17
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
ThroughputControllerTestPlan.jmx
72
Chapter 5 ■ JMeter Test Plan Components
6.
Click on Throughput Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP
Request. Configure Name as beta, Path as /jmeter/beta, and Method as GET.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-44.
73
Chapter 5 ■ JMeter Test Plan Components
The /jmeter/beta HTTP request, being the child element of the Throughput Controller, was executed
only three times, as configured in the Throughput count. The /jmeter/alpha HTTP request, being outside of
the Throughput Controller, was executed for a full 10 times, as configured in the thread group’s Loop Count.
The various combinations of configurations are summarized in Table 5-2.
Threads Loop Per User Mode Throughput Req Count Req. Count
(Users) Count (/jmeter/alpha) (/jmeter/beta)
1 10 No Count 3 10 3
1 10 No Percent 20 % 10 2
2 10 No Count 3 20 3
2 10 No Percent 20 % 20 4
2 10 Yes Count 3 20 6
2 10 Yes Percent 20 % 20 4
/jmeter/alpha is a direct child element of the thread group and is outside the scope of the Throughput
Controller. The number of requests to the /jmeter/alpha is always determined by the Number of Threads
(users) times the Loop Count configured in the thread group.
/jmeter/beta is a child element under Throughput Controller. The number of requests to the /jmeter/
beta is restricted by the Throughput Controller configuration.
When the Per User flag is enabled and the Throughput Controller is in Total Execution mode, the
number of times the child elements are executed is the Number of Threads (Users) times the Throughput.
When the Throughput Controller is in Percent mode, the result happens to be the same whether or not
the Per User checkbox is enabled. This does not change the execution count when Throughput Controller is
in Percent mode.
18
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
OnceOnlyControllerTestPlan.jmx
74
Chapter 5 ■ JMeter Test Plan Components
4.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add Once Only
Controller. It has no configuration.
5.
Click on Once Only Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP
Request. Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Bravo, Path as /jmeter/bravo, and Method as GET.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Charlie, Path as /jmeter/charlie, and Method as GET.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Delta, Path as /jmeter/delta, and Method as GET.
9.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
11.
Save the test plan.
12.
Run the test.
The results will be similar to those shown in Figure 5-45.
Figure 5-45. Once Only Controller with only one request to alpha
75
Chapter 5 ■ JMeter Test Plan Components
These results indicate that the HTTP request for /jmeter/alpha, the child element of the Once Only
Controller, was executed only two times, which is once per thread, as configured. The HTTP requests for
/jmeter/bravo, /jmeter/charlie, and /jmeter/delta were executed eight times as the Number of Threads
(Users) was 2 and the Loop Count was 4.
Interleave Controller
The Interleave Controller executes only one of its child elements per loop iteration. Each time it iterates, it
picks the next child element in sequence.
A child controller is considered a sub-controller. By default, a sub-controller, including all its children, is
treated as a single unit. If the Ignore Sub-Controller Blocks checkbox is enabled, the grouping implied by the
sub-controller is ignored and the child elements of the sub-controller are treated as the direct child elements
of the Interleave Controller.
The Interleave Controller is used to distribute the requests among a set of URLs. Let’s look at an
example that illustrates the use of the Interleave Controller.
Follow these steps or download InterleaveAndLoopControllerTestPlan.jmx.19
1.
Create a test plan and give it a meaningful name, such as Interleave And Loop
Controller Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP Request
Defaults. Configure Server Name or IP as localhost and Port Number as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add Loop
Controller. Configure Loop Count as 4.
5.
Click on Loop Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Zulu, Path as /jmeter/zulu, and Method as GET.
6.
Click on HTTP Request Zulu and go to Edit ➤ Add ➤ Logic Controller. Add
Interleave Controller. Leave the checkbox titled Ignore Sub-Controller Blocks
unchecked (see Figure 5-46).
19
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
InterleaveAndLoopControllerTestPlan.jmx
76
Chapter 5 ■ JMeter Test Plan Components
7.
Click on Interleave Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP
Request. Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
8.
Click on Interleave Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP
Request. Configure Name as Beta, Path as /jmeter/beta, and Method as GET.
9.
Click on Interleave Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Charlie, Path as /jmeter/charlie, and Method as GET.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
11.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
12.
Save the test plan.
13.
Run the test.
The results will be similar to those shown in Figure 5-47.
77
Chapter 5 ■ JMeter Test Plan Components
These results indicate that the Interleave Controller cycles the requests between Alpha, Beta, and
Charlie for each loop iteration.
The Interleave Controller alternates the requests separately for each thread. You can verify this by
modifying this example in the following steps.
1.
Modify the thread group configuration and update Number of Threads (Users) field to 2.
2.
Run the test.
The results will be similar to those shown in Figure 5-48.
78
Chapter 5 ■ JMeter Test Plan Components
In these results, the Interleave Controller alternates the requests for each thread. That is why we see two
requests for Zulu, Alpha, Zulu, Beta, and so on.
Let’s look at the effect of having controllers as child elements of an Interleave Controller.
Follow these steps or download InterleaveAndSimpleControllerTestPlan.jmx.20
1.
Open InterleaveAndLoopControllerTestPlan.jmx.
2.
Go to File ➤ Save Test Plan As and give it a meaningful name, such as
Interleave And Simple Controller Test.
3.
Click on Interleave Controller and go to Edit ➤ Add ➤ Logic Controller. Add
Simple Controller.
4.
Select Beta and Charlie HTTP requests and drag these requests under the Simple
Controller as child elements.
5.
Save the test plan.
6.
Run the test.
The results will be similar to those shown in Figure 5-49.
These results indicate that the Interleave Controller alternates requests between its two child
elements—Alpha and the Simple Controller. All the elements inside the Simple Controller are treated as a
unit. So the request sequence is Zulu, Alpha, Zulu, Beta, Charlie.
Let’s enable the checkbox and see how the request is distributed.
Follow these steps or download InterleaveWithIngnoreSubControllersTestPlan.jmx.21
20
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
InterleaveAndSimpleControllerTestPlan.jmx
21
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
InterleaveWithIngnoreSubControllersTestPlan.jmx
79
Chapter 5 ■ JMeter Test Plan Components
1.
Open InterleaveAndSimpleControllerTestPlan.jmx.
2.
Go to File ➤ Save Test Plan as and type in a filename, such as
InterleaveWithIngnoreSubControllersTestPlan.jmx.
3.
Give the test plan a meaningful name, such as Interleave Controller With
Ignore Sub Controllers.
4.
Click on Interleave Controller and enable the checkbox Ignore Sub-Controller
Blocks (see Figure 5-50).
5.
Save the test plan.
6.
Run the test.
80
Chapter 5 ■ JMeter Test Plan Components
These results indicate that the elements under the Simple Controller are also getting interleaved. It has
changed the request sequence to Zulu, Alpha, Zulu, Beta, Zulu, Alpha, Zulu, Charlie.
Random Controller
The Random Controller is similar to the Interleave Controller except that the order of interleaving is random
instead of sequential. The configuration is just like the Interleave Controller.
In the previous tests, replace Interleave Controller with Random Controller, run the tests, and then
verify the results.
22
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
RandomOrderControllerTestPlan.jmxx
81
Chapter 5 ■ JMeter Test Plan Components
5.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Bravo, Path as /jmeter/bravo, and Method as GET.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Charlie, Path as /jmeter/charlie, and Method as GET.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Zulu, Path as /jmeter/zulu, and Method as GET.
9.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in
Table.
11.
Save the test plan.
12.
Run the test.
The results will be similar to those shown in Figure 5-52.
These results indicate that all the child samplers were executed in random order.
Switch Controller
The Switch Controller is analogous to the switch/case programming construct. The Switch Controller
executes only one of its child elements after matching the element’s name with the configured Switch value.
If the Switch value is an integer, it executes the child element based on the sequence number.
82
www.allitebooks.com
Chapter 5 ■ JMeter Test Plan Components
5.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Bravo, Path as /jmeter/bravo, and Method as GET.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Charlie, Path as /jmeter/charlie, and Method as GET.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Zulu, Path as /jmeter/zulu, and Method as GET.
9.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
23
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
SwitchControllerTestPlan.jmx
83
Chapter 5 ■ JMeter Test Plan Components
11.
Save the test plan.
12.
Run the test.
The results will be similar to those shown in Figure 5-54.
In these results, we can see that the Switch Controller has matched the Switch value Bravo with its child
of the same name. So the request goes to the HTTP request Bravo.
Let’s see how the Switch Controller behaves when configured with a number.
1.
In the previous test plan, click on Switch Controller and modify the
Switch value to 3.
2.
Run the test. The results will be similar to those shown in Figure 5-55.
The results indicate that the Switch Controller picked the fourth child element as the Switch value was 3.
(Remember that the numbering starts with 0.)
84
Chapter 5 ■ JMeter Test Plan Components
ForEach Controller
The ForEach Controller has one or more child elements over which it iterates. It can be configured with the
following parameters. For each iteration, the ForEach Controller performs the following:
• Forms a sequence number by incrementing the Start Index for loop
(Exclusive) option.
• Forms the name of a user defined variable by concatenating the Input Variable
Prefix, “_” and the sequence number.
• Sets the Output Variable Name to the value obtained by looking up the user defined
variable. This Output Variable Name is then available to the child elements.
The number of iterations is equal to the difference between the Start index and End index. If the Start
index and the End index have not been specified, JMeter can figure those out by looking at the user defined
variables, starting with the Input Variable Prefix string. Such variables need to be in numerical sequence.
Any break in the sequence will cause ForEach Controller to finish.
If the Add “_” Before Number? checkbox is not checked, then “_” is not used in forming the name of the
user defined variable. Let’s look at an example.
Follow these steps or download ForEachControllerTestPlan.jmx.24
1.
Create a test plan and give it a meaningful name, such as ForEach Controller Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP as localhost and
Port Number as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add User
Defined Variables. Configure User Defined Variables add Name/Value pairs as
query_1/"alpha", query_2/"bravo", query_3/"charlie", and query_4/"delta"
(see Figure 5-56).
24
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
ForEachControllerTestPlan.jmx
85
Chapter 5 ■ JMeter Test Plan Components
5.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add ForEach
Controller. Configure Input Variable Prefix as query, Start Index for Loop
(Exclusive) as 0, End Index for Loop (Inclusive) as 4, and Output Variable
Name as foreachOutput. Enable the Add "_" before number? checkbox
(see Figure 5-57).
86
Chapter 5 ■ JMeter Test Plan Components
6.
Click on ForEach Controller and go to Edit ➤ Add ➤ Sampler. Add
HTTP Request. Configure Name as /jmeter/${foreachOutput}, Path as
/jmeter/${foreachOutput}, and Method as GET. Note that we are referencing
the output variable defined in the ForEach Controller.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-58.
These results indicate that the ForEach Controller has set foreachOutput successively to alpha, bravo,
charlie, and delta. This has resulted in the HTTP Request Sampler, configured with the URL of
/jmeter/${foreachOutput}, being invoked with /jmeter/alpha, /jmeter/bravo, /jmeter/charlie, and
/jmeter/delta, respectively.
■■Caution Input Variable Prefix and Output Variable Name are required parameters. If you omit them, there is
no error checking, not even a log message. JMeter will simply stop execution without warning.
If Controller
The If Controller is useful for decision/branching logic. The configuration is simple, with only two
checkboxes.
The Interpret Condition as Variable Expression? checkbox indicates whether the expression is evaluated
as a JavaScript expression (the default) or as a variable expression (compared with the string "true").
87
Chapter 5 ■ JMeter Test Plan Components
The Evaluate for All Children? checkbox indicates whether the condition should be evaluated before
processing each of the child elements. If it’s not checked, the condition is evaluated only when it is
encountered for the first time.
Let’s look at an example by using user defined variables.
Follow these steps or download IfControllerUserDefinedVariableTestPlan.jmx.25
1.
Create a test plan and give it a meaningful name, such as If Controller User
Defined Variable Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP as localhost and Port Number
as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add User
Defined Variables. Configure User Defined Variables add Name/Value pair as
myUserVar/alpha.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Alpha, Path as /jmeter/alpha, and Method as GET.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add Debug Sampler.
Select JMeter Properties as False, JMeter Variables as True, and System
Properties as False.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add If
Controller. Configure Condition (Default JavaScript) as "${myUserVar}" ==
"alpha". Leave the other checkboxes unchecked (see Figure 5-59).
25
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
IfControllerUserDefinedVariableTestPlan.jmx
88
Chapter 5 ■ JMeter Test Plan Components
8.
Click on If Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Bravo, Path as /jmeter/bravo, and Method as GET.
9.
Click on If Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Name as Zulu, Path as /jmeter/zulu, and Method as GET.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
11.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
12.
Save the test plan.
13.
Run the test.
The results will be similar to those shown in Figure 5-60.
Click on View Results Tree and then Debug Sampler and then choose the Response Data tab. You will
see that the user defined variable myUserVar is defined as alpha.
These results indicate that the If Controller has evaluated the expression "{myUserVar}" == "alpha" as
a JavaScript expression and found it to be true, and this resulted in the execution of the child elements bravo
and zulu (see Figure 5-61).
89
Chapter 5 ■ JMeter Test Plan Components
■■Caution If the condition expression has a syntax error or if the variable is not found, JMeter will simply
stop execution without any error popping up. If you have not selected the Interpret Condition as Variable
Expression flag, a few DEBUG logs are generated.
The condition is interpreted as a JavaScript expression (the default) that evaluates to true or false.
If the Interpret Condition as Variable Expression checkbox is enabled, then you can use other expressions.
If you enable the Interpret Condition as Variable Expression checkbox and replace the JavaScript
condition "{myUserVar}" == "alpha" with ${__jexl("{myUserVar}" == "alpha")}, it will produce the
same behavior.
In the previous examples, you used user defined variables to define the conditions in test scripts that
were statically defined. In the following example, let’s see how you can use variables extracted from the
responses.
Follow these steps or download IfControllerDynamicVariableTestPlan.jmx.26
1.
Open IfControllerUserDefinedVariableTestPlan.jmx.
2.
Click on User Defined Variables and go to Edit ➤ Remove.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Post Processor. Add CSS/JQuery
Extractor. Configure CSS/JQuery Expression as title (a representation of the
JQuery selector of $("title")) and Reference Name as myDynVar. This is the
name of the variable that will be set and available for the If Controller.
4.
Add a Debug Sampler after each of the HTTP requests. So you should have three
Debug Samplers, one after each of the HTTP requests, alpha, bravo, and zulu.
This will allow you to examine the variables after the execution of every sampler.
26
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
IfControllerDynamicVariableTestPlan.jmx
90
Chapter 5 ■ JMeter Test Plan Components
5.
Configure the If Controller with the condition "${myDynVar}" == "alpha". Do
not enable any other checkboxes.
6.
Save the test plan.
7.
Run the test.
The results will be similar to those shown in Figure 5-62.
8.
Click on View Results Tree and then on Debug Sampler. Click on the Response
Data tab to check the variable myDynVar; you will find that it has been assigned
to the title of the page. The values were changed to bravo and zulu after further
requests were executed.
The If Controller was placed right after the HTTP sampler alpha. So the variable was set to alpha. The If
Controller evaluated the condition and compared this variable to the value of alpha and found it to be true.
So the child elements bravo and zulu were executed.
Now let’s look at the functionality of the Evaluate for All Children checkbox. As the title indicates,
selecting this checkbox causes the If Controller to evaluate the condition before every child sampler is run.
Let’s illustrate this using the following example.
Follow these steps or download IfControllerDynamicVariableEvaluateChildTestPlan.jmx.27
1.
Open IfControllerUserDefinedVariableTestPlan.jmx.
2.
Click on the If Controller, modify the configuration, and enable the Evaluate for
All Children? checkbox.
27
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/controllers/
IfControllerDynamicVariableEvaluateChildTestPlan.jmx
91
Chapter 5 ■ JMeter Test Plan Components
3.
Run the test.
The results will be similar to those shown in Figure 5-63.
4.
Click on View Results Tree and then on Debug Sampler. Click on the Response
Data tab and check the value of the variable myDynVar; you will find that it has
been assigned to the title of the page.
The If Controller was placed right after the HTTP request alpha. So the variable has been set to alpha.
The If Controller evaluated the condition and compared this variable to the value of alpha and found it to be
true. So the child element bravo was executed.
Since the Evaluate for All Children? checkbox was enabled, the condition is evaluated again before
execution of second child element zulu. But the myDynVar is set to bravo, which is the title of the page that
bravo returned. So the condition check fails and the second child element zulu is not executed.
Timers
When users view a web page, they do not click on every link on that page without reason. The user first has
to read the web page, understand it, and then decide on the next course of action. This process varies from
user to user and from web page to web page. Some web pages require that the user enter input or select files
to upload, which introduces delays. You can simulate these delays by using timers.
The duration of the delay varies highly depending on the context and the user. To obtain a feel for the
kind of delay to use, you can study the web access logs. The other way is to observe the users as they interact
with the web site.
Timers are used to introduce a delay or pause before a sampler is run. In a test plan, even if a timer is
placed after the samplers, it will run before the sampler. If the timer is a child element of a sampler, it will
apply only to that sampler. Otherwise, it will apply to all the samplers in that scope. If multiple timers are in
scope, all the timers will apply before a sampler is executed.
92
Chapter 5 ■ JMeter Test Plan Components
Constant Timer
The Constant Timer introduces a specified delay before the samplers in its scope are executed. The only
configuration is the delay that is needed.
Let’s look at the functionality with the help of an example. We will add a Constant Timer and configure
it with a delay value of 5000 milliseconds or 5 seconds. We will make this a child element of a thread group
so that it applies to all the samplers under the thread group.
Follow these steps or download ConstantTimerTestPlan.jmx.28
1.
Create a test plan and give it a meaningful name, such as Constant Timer Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP as localhost and Port Number
as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Configure Path as
/jmeter/alpha and Method as GET.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Configure Path as
/jmeter/bravo and Method as GET.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Configure Path as
/jmeter/zulu and Method as GET.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Timer. Add Constant Timer.
Configure it with a value of 5000 milliseconds (see Figure 5-64).
28
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/timers/
ConstantTimerTestPlan.jmxx
93
Chapter 5 ■ JMeter Test Plan Components
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
9.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
10.
Save the test plan.
11.
Run the test.
The results will be similar to those shown in Figure 5-65.
In these results, each of the HTTP requests has been delayed by five seconds.
As you saw in the previous example, the Constant Timer delays all the child elements in scope. What
if you wanted to delay only a specific sampler by 5 seconds? You can achieve this by making the Constant
Timer a child element of the sampler to be delayed.
Modify the example as follows:
1.
Drag the Constant Timer and make it a child element of the HTTP request
/jmeter/bravo. Leave the configuration as is (see Figure 5-66).
94
Chapter 5 ■ JMeter Test Plan Components
2.
Save the test plan.
3.
Run the test.
The results will be similar to those shown in Figure 5-67.
In these results, the HTTP request bravo has been delayed by 5 seconds, as it is in the scope of the
Constant Timer. There is no delay before the HTTP request zulu.
Along with the other metrics, the Listeners display the time taken by the samplers. If you want to see
the Timer delay included along with the sampler time, you use a Transaction Controller.
95
Chapter 5 ■ JMeter Test Plan Components
6.
Run the test.
The results will be similar to those shown in Figure 5-69.
29
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/timers/
ConstantTimerAndTransactionCtrlTestPlan.jmx
96
Chapter 5 ■ JMeter Test Plan Components
In these results, the Transaction Controller takes around six seconds, which includes five seconds for
the Timer delay and one second for the /jmeter/bravo sampler.
97
Chapter 5 ■ JMeter Test Plan Components
Let’s assume that the mean value is 10 seconds and the variance is 2 seconds. The delay introduced
would vary as follows:
• 99% of the time, the delay would vary between mean - variance and mean +
variance (between 4 seconds and 16 seconds).
• 95% of the time, the delay would vary between mean - 2 * variance and mean + 2 *
variance (between 6 seconds and 14 seconds).
• 68% of the time, the delay would vary between mean - 3 * variance and mean + 3 *
variance (between 8 seconds and 12 seconds).
Refer to Wikipedia for more details about the Gaussian Distribution.
Let’s look at an example.
Follow these steps or download GaussianTimerTestPlan.jmx.30
1.
Create a test plan and give it a meaningful name, such as Gaussian Timer Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP Request
Defaults. Configure Server Name or IP as localhost and Port Number as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Configure Path as
/jmeter/alpha and Method as GET.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add Loop
Controller. Set the Loop Count to 10.
6.
Click on Loop Controller and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Path as /jmeter/bravo and Method as GET.
7.
Click on the HTTP request /jmeter/bravo and go to Edit ➤ Add ➤ Timer. Add
Gaussian Random Timer. Configure Constant Delay Offset (in Milliseconds) as
10000 and Deviation (in Milliseconds) as 2000 (see Figure 5-71).
30
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/timers/
GaussianTimerTestPlan.jmx
98
Chapter 5 ■ JMeter Test Plan Components
8.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Configure Path as
/jmeter/zulu and Method as GET.
9.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in
Table.
11.
Save the test plan.
12.
Run the test.
The results will be similar to those shown in Figure 5-72.
In these results, each of the requests to /jmeter/bravo has been delayed by a random delay centered
about the mean value of 10 seconds.
99
Chapter 5 ■ JMeter Test Plan Components
8.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Configure Path as
/jmeter/zulu and Method as GET.
9.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in
Table.
31
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/timers/
UniformRandomTimerTestPlan.jmx
100
Chapter 5 ■ JMeter Test Plan Components
11.
Save the test plan.
12.
Run the test.
The results will be similar to those shown in Figure 5-74.
In these results, each of the requests to /jmeter/bravo has been delayed by a random delay varying
between 10 and 15 seconds.
32
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/timers/
ConstantThroughputTimerTestPlan.jmx
101
Chapter 5 ■ JMeter Test Plan Components
5.
Click on Thread Group and go to Edit ➤ Add ➤ Timer. Add Constant Throughput
Timer. Configure Target Throughput (in Samples per Minute) as 4.0 and
Calculate Throughput Based on as All Active Threads (Shared)
(see Figure 5-75).
Figure 5-75. Constant Throughput Timer set to four requests per minute
6.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add Aggregate Report.
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-76.
102
Chapter 5 ■ JMeter Test Plan Components
In these results, each of the requests to /jmeter/alpha has been delayed by a varying amount so as to
keep the overall throughput at the configured level (see Figure 5-77).
In the Aggregate results, observe that the throughput is 4.4 requests per minute, which is close enough
to the configured value of 4 requests per minute.
Synchronizing Timer
The Synchronizing Timer blocks threads and releases them all at once, thus creating a large load at the same
instant. This is very helpful to test how the application handles simultaneous requests.
Let’s illustrate this with an example.
Follow these steps or download SynchronizingTimerTestPlan.jmx.33
1.
Create a test plan and give it a meaningful name, such as Constant Throughput
Timer Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure Number of Threads (Users) as 4, Loop Count as 12, and Ramp-Up as 0.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP as localhost and Port Number
as 8080.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Configure Path as
/jmeter/alpha and Method as GET.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Timer. Add Synchronizing
Timer. Configure Number of Simulated Users to Group by as 2 and Timeout in
Milliseconds as 3000 (see Figure 5-78).
33
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/timers/
SynchronizingTimerTestPlan.jmx
103
Chapter 5 ■ JMeter Test Plan Components
6.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in Table.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add Aggregate Report.
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-79.
104
Chapter 5 ■ JMeter Test Plan Components
In these results, each of the requests to /jmeter/alpha has been delayed so that both the samples are
released at the same time, as marked in red.
Sampler
The Sampler is a component that’s used to send requests to the application being tested. If the test plan has
more than one sampler, they will be executed in the order they are defined in the test plan tree.
JMeter has the following samplers as of release 3.0:
• Access Log Sampler
• AJP/1.3 Sampler
• BeanShell Sampler
• BSF Sampler
• Debug Sampler
• FTP Request
• HTTP Request
105
Chapter 5 ■ JMeter Test Plan Components
• Java Request
• JDBC Request
• JMS Point-to-Point
• JMS Publisher
• JMS Subscriber
• JSR233 Sampler
• JUnit Request
• LDAP Extended Request
• LDAP Request
• Mail Reader Sampler
• OS Process Sampler
• SMTP Sampler
• SOAP/XML-RPC Request
• TCP Sampler
• Test Action
Sampler properties can be configured as per requirements. However, most of the time, the default
configuration is sufficient.
Each of the samplers generates one or more sample results (the exception is Test Action). These
sampler results have various attributes, such as success/fail/elapsed time, etc., which are viewed by using
various listeners.
With each sampler, you should use assertions to make sure that the sampler is working as per your
requirements. For example, you would use response assertions for the HTTP request to check for status 200.
HTTP Request
The HTTP Request sampler is used when you want to use POST, GET, DELETE, PUT, etc., methods over HTTP(S)
on the target web application (Sampler AJP/1.3 sampler also has these methods).
The minimum configuration required for a HTTP Request test element to work is the server name or
IP. If the port number is 80, it can be omitted. You can specify timeouts (in milliseconds) while waiting for a
response from the server.
JMeter provides several properties to configure the HTTP Request sampler. Let’s walk through each of
these with examples.
106
Chapter 5 ■ JMeter Test Plan Components
If it’s not defined, it relies on the jmeter.httpSampler property defined in the jmeter.properties file,
failing which it defaults to HttpClient4.
HTTPClient internally uses Apache HTTP components.34
A request with a blank value or HTTPClient will send a HTTP header for UserAgent with a value of
Apache-HttpClient/4.2.6 (java 1.5). However, if the implementation type is Java, then the HTTP header
for UserAgent will not be sent.
Let’s look at the following example.
Follow these steps or download HTTPClientImplTestPlan.jmx.35
1.
Create a test plan and give it a meaningful name, such as HTTP Client
Implementation Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signIn, and Method as POST. Choose Implementation as Java from the
drop-down. Add the parameters, Name/Value as email/[email protected] and
password/user1.
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signOut, and Method as HEAD. Leave the Implementation as blank.
7.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree
(see Figure 5-80).
34
https://hc.apache.org/httpcomponents-client-ga
35
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/samplers/
HTTPClientImplTestPlan.jmx
107
Chapter 5 ■ JMeter Test Plan Components
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-81.
In these results, you will not see the User-Agent header in the first HTTP request, due to the
Implementation option being set to Java (see Figure 5-82).
108
Chapter 5 ■ JMeter Test Plan Components
Protocols
JMeter provides http, https, and file protocols. We have already walked through the http protocol. Now,
let’s look at the procedure to record the tests on web sites that use the https protocol.
From JMeter 2.11 onwards, a dummy certificate is created in the /bin directory as soon as you start the
proxy server from the HTTP(S) Test Script Recorder. It creates two files, which you can see under the /bin
directory.
C:\apache-jmeter-3.0>cd bin
C:\apache-jmeter-3.0\bin>Dir ApacheJMeter*
Volume in drive C has no label.
Volume Serial Number is DA32-01EE
Directory of C:\apache-jmeter-3.0\bin
C:\apache-jmeter-3.0\bin>
We need to import ApacheJMeterTemporaryRootCA.crt into the browser being used for recording.
Let’s see this with the help of the following example, using the Firefox browser.
1.
Open JMeter GUI.
2.
Click on WorkBench and go to Edit ➤ Add ➤ Non-Test Elements. Add HTTP(S)
Test Script Recorder. Configure the Target Controller by selecting WorkBench ➤
HTTP(s) Test Script Recorder.
3.
Launch the Firefox browser and go to Preferences ➤ Advanced ➤
Certificates ➤ View Certificates. Click on Import, and then select the
ApacheJMeterTemporaryRootCA.crt certificate (see Figure 5-83).
109
Chapter 5 ■ JMeter Test Plan Components
4.
Open the Firefox browser and launch https://in.yahoo.com.
5.
Stop recording.
6.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
7.
Move all the recorded samplers as child elements of the thread group.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
9.
Run the test and you will see that the https requests are getting executed.
Redirect Automatically
The Redirect Automatically configuration field sets the underlying http protocol handler to automatically
follow redirects. They are not seen by JMeter and thus will not appear as samples. This will be helpful when
you don’t want to see the requests that are redirected. This should only be used for GET and HEAD requests, as
the HttpClient sampler will reject attempts to use it for POST or PUT.
You can use either the Redirect Automatically or Follow Redirects configuration property, but not both
at the same time.
Let’s illustrate this by the following example.
Follow these steps or download RedirectAutoTestPlan.jmx.36
1.
Create a test plan and give it a meaningful name, such as Redirect
Automatically Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
36
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/samplers/
RedirectAutoTestPlan.jmx
110
Chapter 5 ■ JMeter Test Plan Components
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as /
user/signIn, and Method as POST. Add the parameters, Name/ Value as email/
[email protected] and password/user1.
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signOut, and Method as HEAD. Enable the Redirect Automatically
checkbox (see Figure 5-84).
7.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200 (see Figure 5-85).
111
Chapter 5 ■ JMeter Test Plan Components
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-86.
Follow Redirect
On the web, the URLs for the web pages or resources change frequently. The browser is informed of the new
URL by the concept of URL redirection. This is also referred to as URL forwarding. HTTP status codes 3XX
are used to indicate redirection.
Let’s illustrate this with an example.
Follow these steps or download FollowRedirectTestPlan.jmx.37
1.
Create a test plan and give it a meaningful name, such as Follow Redirect Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signIn, and Method as POST. Add the parameters, Name/ Value as
email/[email protected] and password/user1.
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code,
Pattern Matching Rules as Equals, and Patterns To Test as 200.
37
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/samplers/
FollowRedirectTestPlan.jmx
112
Chapter 5 ■ JMeter Test Plan Components
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signOut, and Method as HEAD. By default, the Follow Redirects flag is
enabled (see Figure 5-87).
7.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree
(see Figure 5-88).
9.
Save the test plan.
10.
Run the test.
113
Chapter 5 ■ JMeter Test Plan Components
11.
Remove the selection of Follow Redirects flag in the HTTP Request sampler.
12.
Run the test.
The results will be similar to those shown in Figure 5-90.
In this case, assertions has been configured to match the Response Code of 200. But the redirected
response code received was 302, so the test failed.
114
Chapter 5 ■ JMeter Test Plan Components
Use KeepAlive
The Use KeepAlive checkbox is enabled by default. This allows the same connection to be re-used by
including KeepAlive in the Connection header.
Let’s illustrate this by the following example.
Follow these steps or download KeepAliveTestPlan.jmx.38
1.
Create a test plan and give it a meaningful name, such as Keep Alive Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signIn, and Method as POST. Add the parameters, Name/ Value as
email/[email protected] and password/user1.
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signOut, and Method as HEAD. Disable the Use KeepAlive checkbox.
7.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree
(see Figure 5-91).
38
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/samplers/KeepAliveTestPlan.jmx
115
Chapter 5 ■ JMeter Test Plan Components
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-92.
■■Note If you disable the KeepAlive configuration option for the last request, then the next request will use
a new connection.
Browser-Compatible Headers
This property is used in combination with multipart/form-data for POST. Using this suppresses the
Content-Type and Content-Transfer-Encoding Headers. Only the Content-Disposition Header is sent.
When it’s not checked, it will use Content-Transfer-Encoding: binary.
116
Chapter 5 ■ JMeter Test Plan Components
Body Data
For Body Data, you need to prepare an URL if it has special characters.
URL encoding starts with % and then includes the equivalent Hexadecimal code; refer to asciitable39
to determine the other special characters in an URL.
Let’s illustrate this by the following example.
Follow these steps or download BodyDataTestPlan.jmx.40
1.
Create a test plan and give it a meaningful name, such as Body Data Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
39
http://www.asciitable.com
40
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/samplers/BodyDataTestPlan.jmx
117
Chapter 5 ■ JMeter Test Plan Components
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signIn, and Method as POST. Click on Body Data and add the post
parameters as email=user1%40dt.com&password=user1 (see Figure 5-94).
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code,
Pattern Matching Rules as Equals, and Patterns To Test as 200.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as
/user/signOut.
7.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code,
Pattern Matching Rules as Equals, and Patterns To Test as 200.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree
(see Figure 5-95).
118
Chapter 5 ■ JMeter Test Plan Components
9.
Save the test plan.
10.
Run the test.
The results will be similar to those shown in Figure 5-96.
119
Chapter 5 ■ JMeter Test Plan Components
41
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/samplers/FileLoadTestPlan.jmx
120
Chapter 5 ■ JMeter Test Plan Components
7.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code,
Pattern Matching Rules as Equals, and Patterns To Test as 200.
8.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Document (text),
Pattern Matching Rules as Contains, and add Pattern To Test as Success!.
Add another pattern as File uploaded successfully.
9.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree
(see Figure 5-99).
121
Chapter 5 ■ JMeter Test Plan Components
10.
Save the test plan.
11.
Run the test.
The results will be similar to those shown in Figure 5-100.
The MIME type is the content type of the file being used in the request. It is good practice to provide the
MIME type, as the web server may behave based on the MIME type and on the application being tested.
The parameter name used in the HTTP request is taken from the HTML code (see Figure 5-101).
122
Chapter 5 ■ JMeter Test Plan Components
JMeter provides a few additional configuration points that can be used based on specific requirements.
• Proxy Server (if an application being tested reached through the proxy server)
• Embedded Resources for HTML Files
• Source Address
• Option Tasks
Proxy Server
JMeter provides a simple way to specify the proxy server details for the HTTP Request sampler. This property
is only applicable to the current request. You can specify the proxy server name and the port number if
needed. In addition, you may also need to specify a username and password.
123
Chapter 5 ■ JMeter Test Plan Components
42
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/samplers/
EmbeddedResourceTestPlan.jmx
124
Chapter 5 ■ JMeter Test Plan Components
5.
Save the test plan.
6.
Run the test.
The results will be similar to those shown in Figure 5-103.
7.
Click on HTTP Request and then click on the Advanced tab. Under Embedded Resources
from HTML Files, select the checkbox for Retrieve All Embedded Resources
8.
Save the test plan.
Run the test again and you will see a lot of requests, as shown in Figure 5-104.
125
Chapter 5 ■ JMeter Test Plan Components
There is one JMeter property added after the 2.1.2 release, called HTTPResponse.parsers. This can be
separated with a space, as in htmlParser wmlParser. For each ID found, JMeter checks two more properties.
• id.types: A list of content types
• id.className: The parser used to extract the embedded resources
If the HTTPResponse.parser property is not set, then JMeter reverts to the previous behavior, i.e., only
text/HTML responses will be scanned.
Source Address
This property is only used with HTTP requests that use the HTTPClient implementation. This property is
used to enable IP spoofing.
IP spoofing is a technique used to gain unauthorized access to machines. In this, the attacker
impersonates another machine by modifying the packet header with a spoofed source IP address.
If the property httpclient.localaddress is defined, it is used for all HttpClient requests.
This property is very rarely used under specific scenarios.
Option Task
This has two properties:
• Use as Monitor: This will be used with the Monitor Results listener.
• Save Response as MD5 Hash?: By using this property, the response will be encoded
in MD5 hash code.
Let’s look at the following example.
Follow these steps or download MD5TestPlan.jmx.43
1.
Create a test plan and give it a meaningful name, such as MD5 Hash Code Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/dt, and Method as GET.
4.
Click on the Advanced tab and select the Save Response as MD5 Hash?
checkbox.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree
(see Figure 5-105).
43
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/samplers/MD5TestPlan.jmx
126
Chapter 5 ■ JMeter Test Plan Components
6.
Save the test plan.
7.
Run the test.
The results will be similar to those shown in Figure 5-106.
■■Note Use HTTP(S) Test Script Recorder to record the user actions and add HTTP Request Defaults and
Config Element to capture the common parameters for all successive requests.
127
Chapter 5 ■ JMeter Test Plan Components
Assertions
The primary purpose of assertions is to validate the server response and decide if the test passed or failed.
The response to a sampler contains code to indicate success or error. But this is at the protocol level.
JMeter assertions provides a mechanism to validate the content of the response. The specific JMeter assertions
you use depend on the response format. The validation check is configurable based on the assertions type.
JMeter assertions can be a child element of a test plan, thread group, controller, or sampler. Assertions
will apply to all the samplers under the scope of its parent. For example, if an assertion is a child element of a
thread group, then it applies to all the samplers under the thread group. Sometimes, it makes more sense to
have specific assertions for each sampler. JMeter provides the flexibility to add multiple assertions.
Assertions are used to validate the test script. Since they consume CPU and memory resources, you
should remove or disable them before running the performance test to gather statistics.
The Assertion Results listener is a special listener intended specifically for viewing the results of assertions.
In the following examples, you will be using the View Results Tree listener during the test script
development. However, it will be removed before you have to gather the final performance numbers.
■■Tip Use assertions and the Assertion Results listener with discretion, as they consume CPU and memory.
Response Assertion
The Response Assertion provides various options to validate the response from a sampler (see Figure 5-107).
There are four categories of properties provided by JMeter assertions, discussed next.
128
Chapter 5 ■ JMeter Test Plan Components
Apply to Property
This option specifies where to apply the assertions: Main sample and sub-samples, main sample only,
Sub-samples only, and JMeter variable. Sometimes a sampler may generate a redirected URL, which in turn
will appear as a sub-sample and it is possible to apply assertions to these sub-samples by using Sub-Samples
Only option. If you are using variables inside the test script, you can use JMeter variable option to validate it.
129
Chapter 5 ■ JMeter Test Plan Components
Enabling the Not checkbox negates the operator. For example, select Not and Equals to make the rule
Not Equals.
Refer to the ORO covering Perl5 regular expressions44 and also look at the JMeter User Manual for more
information.45
44
https://www.savarese.org/oro/docs/OROMatcher/Syntax.html#Perl5Expressions
45
http://jmeter.apache.org/usermanual/regular_expressions.html
46
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/assertions/
SamplerAssertionsTestPlan.jmx
130
Chapter 5 ■ JMeter Test Plan Components
7.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Give it a name such as Main Sample Only-Response CodeEquals
Not & Ignore Status. Configure Apply To by selecting Main samples only, set
Response Field to Test by selecting Response Code, enable the Ignore Status
checkbox, set the Pattern Matching Rule by selecting Equals, and select the Not
checkbox. For Pattern To Test, add 500. (You have selected the Ignore Status
checkbox, which states that ignore the URL status is successful; this will not be an
ideal condition with the response code set to 5XX or 4XX) (see Figure 5-109).
Figure 5-109. Main sample only, response code equals not ignore status
131
Chapter 5 ■ JMeter Test Plan Components
8.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Give it a name such as Main Sample Only-Text ResponseContains
Not & Ignore Status. Configure Apply To as Main samples only and
Response Field to Test as Text Response. Select the Ignore Status checkbox.
Set the Pattern Matching Rule to Contains and then select the Not checkbox.
Set the Pattern To Test to (?:URL not found) (see Figure 5-110).
Figure 5-110. Main sample only, text response contains not ignore status
9.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Give it a name such as Main Sample Only-Document (text)-
Substring. Configure Apply To as Main samples only, Response Field to Test
as Document (text), Pattern Matching Rule as Substring, and Pattern To Test
as <title>Digital Toys Inc - the electronic goods e-store.</title>
(see Figure 5-111).
132
Chapter 5 ■ JMeter Test Plan Components
10.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Give it a name such as Sub-Samples Only-URL SampledSubstring
Not. Configure Apply To as Sub-samples only, Response Field to Test as URL
Sampled, and Pattern Matching Rule as Substring. Select the Not checkbox and
set Pattern To Test to Error (see Figure 5-112).
133
Chapter 5 ■ JMeter Test Plan Components
11.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure the Path as dt/index and the Method as GET.
12.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Give it a name as Main Sample Only-Response CodeEquals.
Configure Apply To as Main samples only, Response Field to Test as Response
Code, Pattern Matching Rule as Equals, and Pattern To Test as 200
(see Figure 5-113).
13.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Give it a name such as Main Sample Only-Response Message-Equals.
Configure Apply To as Main samples only, Response Field to Test as Response
Message, Pattern Matching Rule as Equals, and Pattern To Test as OK
(see Figure 5-114).
134
Chapter 5 ■ JMeter Test Plan Components
14.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Give it a name such as Main Sample Only-Response Headers-
Contains. Configure Apply To as Main samples only, Response Field to Test as
Response Headers, Pattern Matching Rule as Contains, and Pattern To Test as
(1?)HTTP/1.1 200 OK (see Figure 5-115).
135
Chapter 5 ■ JMeter Test Plan Components
15.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Path as /user/signOut and Method as HEAD.
16.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Give it a name such as Main Sample and Sub-SamplesText
Response-Matches Not. Configure Apply To as Main samples and sub-
samples, Response Field to Test as Text Response, and Pattern Matching Rule
as Matches. Select the Not checkbox set the Pattern To Test to (?:Good Shot
Camera) (see Figure 5-116).
Figure 5-116. Main sample and sub-samples text response, matches not
17.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
18.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add Assertion Results
(see Figure 5-117).
136
Chapter 5 ■ JMeter Test Plan Components
19.
Save the test plan.
20.
Run the test.
The results will be similar to those shown in Figure 5-118.
137
Chapter 5 ■ JMeter Test Plan Components
Listener
Listeners capture and process the response from the server. Performance testing requires two kinds of
listeners. During the test script development, you need to capture and display the entire server response
for verifying that the output meets the functional specifications. When the performance test scripts are
executed, you need the aggregate results and metrics for the duration of the test execution. You also need
listeners to be able to store these results into an external file for later use.
JMeter Listeners can be configured to capture the required information by selecting individual fields
provided by the JMeter Listener. The test plan can have more than one listener and they are executed after all
the other types of elements in the test plan.
Listeners consume memory and CPU time to perform I/O and to process the results and generate
reports. In Master/Slave mode, it is important to choose the right listeners and as few as possible, because
slave nodes will write data back to the master node and overall it will slow down processing or dry out
memory.
138
Chapter 5 ■ JMeter Test Plan Components
As of JMeter version 3.0, the following listeners are available, but only a few are used frequently:
• Aggregate Graph
• Aggregate Report
• Assertion Results
• Backend Listener
• BeanShell Listener
• BSF Listener
• Comparison Assertion Analyzer
• Generate Summary Results
• Graph Results
• JSR233 Listener
• Mailer Visualizer
• Monitor Results
• Response Time Graph
• Save Responses to a File
• Simple Data Writer
• Summary Report
• View Results in Table
• View Results in Tree
Most of these listeners—except for Backend Listener, BeanShell Listener, BSF Listener, Generate
Summary Results, JSR233 Listener, and Save Responses to a File—can be configured using the Configure
button on the right side.
Listeners allow you to save data in CSV/XML formats. Bear in mind that XML files consume more
memory than CSV files (see Figure 5-120).
139
Chapter 5 ■ JMeter Test Plan Components
■■Note All JMeter Listeners store similar data to the external file, but GUI presentation is different.
All of the configuration parameters can be configured through the jmeter.properties file.
Set the following property to either CSV or XML:
# legitimate values: xml, csv, db. Only xml and csv are currently supported. #jmeter.save.
saveservice.output_format=csv
Other configuration fields can be set in jmeter.properties, and all these parameters can be found with
the prefix jmeter.save.saveservice.
JMeter supports additional sample variables you can specify, as shown here. They will appear in the
CSV/XML file as additional fields.
# Optional list of JMeter variable names whose values are to be saved in the result data
files. # Use commas to separate the names. For example:
#sample_variables=SESSION_ID,REFERENCE
140
Chapter 5 ■ JMeter Test Plan Components
JMeter Listeners follow the SimpleDataFormat.47 JMeter first tries to parse this as a long integer. Failing
that, it will try the following formats.
Matching is strict (non-lenient). JMeter 2.8 and earlier used lenient mode, which could result in
timestamps with incorrect dates (times were usually correct).
The most commonly used listeners are View Results Tree, View Results in Table, and Aggregate Report.
Let’s discuss these in the following sections.
47
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
48
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/listeners/
ViewResultsTreeTestPlan.jmx
141
Chapter 5 ■ JMeter Test Plan Components
7.
Save the test plan.
8.
Run the test.
The results will be similar to those shown in Figure 5-122.
142
Chapter 5 ■ JMeter Test Plan Components
9.
The View Results Tree has an option to search for the request. You enter the
HTTP request name in the search box and click on Search button. The matched
request will appear in red (see Figure 5-123).
10.
Look at the sampler results, parsed format. It has the same information as in raw
format but in a tabular format and is more human-readable (see Figure 5-124).
143
Chapter 5 ■ JMeter Test Plan Components
11.
Look at the Request - Raw format as well (see Figure 5-125).
12.
Look at the Request - HTTP format as well. It has the same information as in raw
format, but in a tabular format and is more human-readable (see Figure 5-126).
144
Chapter 5 ■ JMeter Test Plan Components
13.
Look at the Response Filters field. It has search options based on response filters
and works on the visible text. For each filter type, there will be different text
visible on the panel, so make sure that if you are searching for HTML-related text
to open the response data with an HTML filter. The regular expression uses the
Java engine (not an ORO engine like the Regular Expression Extractor or RegExp
Tester view) (see Figure 5-127).
If you want to change the default size of the response data, use the following jmeter.properties
property.
# Maximum size of Document that can be parsed by Tika engine; default=10 * 1024 * 1024
(10MB) # Set to 0 to disable the size check
#document.max_size=0
145
Chapter 5 ■ JMeter Test Plan Components
This listener also provides an option to save results to a file (see Figure 5-128).
Figure 5-128. Filename
Provide the name of the file and it will save the file inside the /bin directory of JMeter. If you provide
a full path, the file will be saved inside that directory. The generated file is a comma-separated file with the
default configuration.
Look at the contents of the file. Contents may differ based on your configuration of listeners, but the
original objective is the save the results to a file.
c:\apache-jmeter-3.0\bin>type results.csv
1454179982085,3355,HTTP Request,200,OK,Thread Group 1-2,text,true,279689,10,10,456
1454179982187,3418,HTTP Request,200,OK,Thread Group 1-3,text,true,279725,9,9,472
1454179982386,3267,HTTP Request,200,OK,Thread Group 1-5,text,true,279709,8,8,468
1454179982289,3433,HTTP Request,200,OK,Thread Group 1-4,text,true,279695,7,7,476
1454179981982,3772,HTTP Request,200,OK,Thread Group 1-1,text,true,279750,6,6,467
1454179982484,3318,HTTP Request,200,OK,Thread Group 1-6,text,true,279650,5,5,465
1454179982586,3254,HTTP Request,200,OK,Thread Group 1-7,text,true,279760,4,4,470
1454179982687,3244,HTTP Request,200,OK,Thread Group 1-8,text,true,279709,3,3,461
1454179982788,3299,HTTP Request,200,OK,Thread Group 1-9,text,true,279750,2,2,468
1454179982888,3248,HTTP Request,200,OK,Thread Group 1-10,text,true,279707,1,1,458
Non-GUI Mode
When you are running tests in non-GUI mode and want to see results in this listener, pass the -l flag with the
filename in the command.
146
Chapter 5 ■ JMeter Test Plan Components
■■Note By default, if you run tests in non-GUI mode, the test results are appended to an .jtl file. Make sure
that you delete .jtl files appropriately.
Open the View Results Tree and from the section called Write Results to File/Read from File. Click on
the Browser button and locate the file (generated using the command) and the tree view will be visible on
GUI (see Figure 5-129).
You can filter logs based on errors or successes, or both, by using the checkbox.
If you have not set the custom fields for the results file configuration section, you will not see any output
under the Request or Response data panels.
Stop JMeter and set the following parameters in the $JMETER_HOME\bin\user.properties file.
Re-run test in non-GUI mode and open the .jtl file generated by the listener. It will show all the details
just like when you have executed tests in GUI mode.
■■Caution View Results Tree takes lot of memory to hold results and should not be used while doing actual
performance testing.
147
Chapter 5 ■ JMeter Test Plan Components
• Status: It has two statuses: 1. Success, 2. Warning. If the thread sample is not valid, it
shows Warning; otherwise, it shows Success.
• Bytes: Total number of bytes received as a part of the response.
• Latency: JMeter measures the latency from just before sending the request to just
after the first response is received.
• Connect Time(ms): JMeter measures the time it takes to establish the connection,
including the SSL handshake.
Let’s illustrate this with the following example.
Follow these steps or download ViewResultsInTableTestPlan.jmx.49
1.
Create a test plan and give it a meaningful name, such as View Results In
Table Listener Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Header Manager.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as /dt.
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results in
Table (see Figure 5-130).
49
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/listeners/
ViewResultsInTableTestPlan.jmx
148
Chapter 5 ■ JMeter Test Plan Components
7.
Save the test plan.
8.
Run the test.
The results will be similar to those shown in Figure 5-131.
Provide the name of the file and it will save the file inside the /bin directory of JMeter. If you provide full
path, the file will be saved inside that directory. The generated file is a comma-separated file with the default
configuration.
Non-GUI Mode
When running tests in non-GUI mode, you want to see results in this listener pass l flag with the filename in
the command.
Open View Results in Table and locate the section Write Results to File/Read from File. Click on the
Browser button and locate the file (generated using the command). The tree view will be visible on GUI. It
will show the connection time as 0.
You can filter logs based on errors or successes, or both, by using that checkbox.
■■Caution View Results in Table takes lot of memory to hold results and should not be used while doing
actual performance testing.
149
Chapter 5 ■ JMeter Test Plan Components
Aggregate Report
GUI Mode
The Aggregate Report listener also shows the responses in a table-like structure for each differently named
sampler. Similar to View Results in Table, it does not have a panel and does not show any headers or
response contents. Generated results can be saved as .csv files with the use of the Save Table Data button at
the bottom of this listener.
If you have multiple thread groups in your test script, it is useful to display the thread group name. This
can be achieved by enabling the Include Group Name in Label? checkbox (by default, it’s unchecked). By
enabling the Save Table Header checkbox, you can save headers of the table with the generated results.
For each sampler, it shows the following columns in the view:
• Label: Name given to the sampler. If the Include Group Name in Label? checkbox is
checked, then the thread group name is prefixed with the sampler name.
• Samples: Number of samples for a sampler. If there is more than one sampler with
the same name, it will be combined to a single row and the combined sum is shown.
• Average: This is the average time in milliseconds for a set of results.
• Median: This is the median time in milliseconds.
• 90% Line: This is the time in milliseconds below which 90% of the samples fall.
The other samples took at least as long as this.
• 95% Line: This is the time in milliseconds below which 95% of the samples fall.
The other samples took at least as long as this.
• 99% Line: This is the time in milliseconds below which 99% of the samples fall.
The other samples took at least as long as this.
• Min: This the shortest time in milliseconds for the sampler with the same name.
• Max: This the maximum time in milliseconds for the sampler with the same name.
• Error %: Percent of requests with errors; it may be in fractions.
• Throughput: Calculated as requests/unit of time. It is the time difference between
the end of the last sample and the start of the first sample, including any gaps
between samples. It is expressed as number of requests/total time.
• KB/sec: The response received in kilobytes per second.
Let’s illustrate this by the following example.
Follow these steps or download AggregateReportTestPlan.jmx.50
1.
Create a test plan and give it a meaningful name, such as Aggregate Report
Listener Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Header Manager.
50
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/listeners/
AggregateReportTestPlan.jmx
150
Chapter 5 ■ JMeter Test Plan Components
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as /dt.
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code,
Pattern Matching Rules as Equals, and Patterns To Test as 200.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add Aggregate Report
(see Figure 5-132).
7.
Save the test plan.
8.
Run the test.
The results will be similar to those shown in Figure 5-133.
151
Chapter 5 ■ JMeter Test Plan Components
Provide the name of the file and it will save the file inside the /bin directory of JMeter. If you provide full
path, the file will be saved inside that directory. The generated file is a comma-separated file with the default
configuration.
After opening the generated XML file, you can see an XML representation with a default configuration.
Searching for httpSample shows the HTTP request used in the test.
Non-GUI Mode
When running tests in non-GUI mode, if you want to see results in this listener, pass the -l flag with the
filename in the command.
Open Aggregate Report and find the section Write Results to File/Read from File. Click on the Browser
button and locate the file (generated using the command). The tree view will be visible on GUI.
You can filter logs based on errors or successes, or both, by using that checkbox.
■■Note Aggregate Report Listener no longer keeps copies of every single sample. Instead, it aggregates and
keeps only the summary report. This listener is suitable for actual performance testing.
Post-Processors
After the sampler gets executed, you need a post-processor to extract useful information from the response
and store the value in a variable to make it available to the next sampler. Post-processors are executed before
the listener and after the sampler, as per the JMeter test plan execution order.
152
Chapter 5 ■ JMeter Test Plan Components
51
http://jmeter.apache.org/usermanual/regular_expressions.html
153
Chapter 5 ■ JMeter Test Plan Components
• Template: This is used to create a string from the matches found by the regular
expression. $1$ refers to the first group, $2$ refers to the second group, and $0$ refers
to the whole expression matched string.
• Match No. (0 for Random): This signifies which match to use in case there are
multiple matches found by the regular expression.
• Default Value: This is used to set the default value for Reference Name in case the
regular expression does not result any matches.
Let’s say that you configure the Reference Name as cardId. JMeter will store these as follows:
• cardId: Original variable name or reference name
• cardId_gn: Where gn is the group number
• cardId_g: Where g is the total number of groups.
If you set the Match No. (0 for Random) to -ve then all possible matches in the sampler response data
are processed.
• cardId_matchNr: Number of matches found. If none are found then it will be zero
• cardId_n: Number of strings generated by the template
• cardId_n_gm: gm groups for n matches
• cardId: Default value will be used
• cardId_gn: This will not be set in this case
Let’s illustrate these with the following example. (For the test script example, we will be using Apply To
as Main sample only and Field to Check as Body.)
Before starting the test, let’s set up the browser for recording steps on JMeter. Set the browser and
JMeter HTTP(S) test script recorder, and the global settings port to the same port.
Next, let’s set up proxy in Firefox browser.
1.
Open Firefox browser and select Preferences ➤ Advanced ➤ Network ➤
Connection Settings ➤ Manual Proxy Configuration. Configure HTTP Proxy as
localhost and Port as 7070.
2.
Select Use this Proxy Server for All Protocols.
3.
Remove anything under No Proxy for. text Area and then click OK.
The Firefox browser is now set up to send HTTP requests to the JMeter proxy.
Follow these steps or download RegularExpressionExtractorTestPlan.jmx.52
1.
Create a test plan and give it a meaningful name, such as Regular Expression
Extractor Test.
2.
Click on WorkBench and go to Edit ➤ Add ➤ Non-Test Elements. Add HTTP(S)
Script Test Recorder. Configure Global Settings, Port as 7070. Select Target
Controller as WorkBench > HTTP(S) Test Script Recorder.
3.
Add Exclude Regular Expression As: .*\.(css|js|ico|ttf|woff).\*
4.
Click on the Start button and confirm the dialog box by clicking OK.
52
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/post-processors/
RegularExpressionExtractorTestPlan.jmx
154
Chapter 5 ■ JMeter Test Plan Components
5.
Open the Firefox browser and follow the steps to update the payment
information.
6.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP Request
Defaults. Configure Server Name or IP as localhost and Port Number as 8080.
8.
Select all recorded browser actions from WorkBench. Drag and add them as child
elements of the thread group.
9.
Click on each HTTP request and remove the Server Name or IP and Port
Number options. (We have configured these in HTTP Request Defaults.)
10.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add Debug Sampler.
Move this to above the /user/signOut HTTP sampler.
11.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
12.
Save the test plan.
Follow these additional steps to configure the Regular Expression Extractor.
1.
Click on the first HTTP request called /user/addCard and go to Edit ➤ Add ➤
Post Processors. Add Regular Expression Extractor. Configure the options as
shown in Figure 5-135.
155
Chapter 5 ■ JMeter Test Plan Components
2.
Click on the second HTTP request called /user/addCard and configure the
options as shown in Figure 5-136. (You need to update the card ID, which you are
extracting from an earlier request).
3.
Run the test.
156
Chapter 5 ■ JMeter Test Plan Components
4.
You can also click on Debug Sampler to cross-verify the value of cardId after Post-
Processor has parsed the value from the sampler response (see Figure 5-138).
Once the JMeter test is executed, open your browser and launch the Digital Toys Inc. web application.
Log in again as [email protected]/user1, navigate to the payment information, and verify the updated
information.
157
Chapter 5 ■ JMeter Test Plan Components
Figure 5-139 shows a big picture view of the properties, variables, and user defined variables.
Notice that the variables are local to a thread group, whereas the modifications to the properties are
shared across the thread groups.
Let’s illustrate this by the following example.
Follow these steps or download PropertiesAndVariablesTestPlan.jmx.53
1.
Create a test plan and give it a meaningful name, such as User Defined
Variables Test. Enable the Run Thread Groups Consecutively (i.e. Run
Groups One at a Time) checkbox.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure the name as Thread Group A and the Loop Count as 1.
53
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/properties-and-variables/
PropertiesAndVariablesTestPlan.jmx
158
Chapter 5 ■ JMeter Test Plan Components
3.
Click on Thread Group A and go to Edit ➤ Add ➤ Pre Processor. Add JSR223
Pre Processor. Configure Script Language as Java and enter this script: vars.
put("zeta_variable", "variable value");props.put("Alpha_variable",
"property value");. See Figure 5-140.
4.
Click on Thread Group A and go to Edit ➤ Add ➤ Sampler. Add Debug Sampler.
Configure JMeter Properties as True, JMeter Variables as True, and System
Properties as False (see Figure 5-141).
159
Chapter 5 ■ JMeter Test Plan Components
5.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure the name as Thread Group B and the Loop Count as 1.
6.
Click on Thread Group B and go to Edit ➤ Add ➤ Sampler. Add Debug Sampler.
Configure JMeter Properties as True, JMeter Variables as True, and System
Properties as False.
7.
Click on Test Plan and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
8.
Save the test plan.
9.
Run the test.
The results are as shown in Figure 5-142.
Observe that the user parameter zeta_variable defined in Thread Group A is not visible in Thread
Group B. However, the property alpha_property defined in Thread Group A is global and is visible in
Thread Group B as well (see Figure 5-143).
160
Chapter 5 ■ JMeter Test Plan Components
54
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/properties-and-variables/
UDVExecuteThreadGroupConsecutivelyTestPlan.jmx
161
Chapter 5 ■ JMeter Test Plan Components
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure the name as Thread Group A and Loop Count as 1.
3.
Click on Thread Group A and go to Edit ➤ Add ➤ Sampler. Add Debug Sampler.
Configure the name as Debug Sampler Thread A.
4.
Click on Thread Group A and go to Edit ➤ Add ➤ Post Processors. Add JSR223
PostProcessor. Configure the language as Java. Add the following in the Script
box (see Figure 5-145).
5.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure the name as Thread Group B and the Loop Count as 1.
6.
Click on Thread Group B and go to Edit ➤ Add ➤ Sampler. Add Debug Sampler.
Configure the name as Debug Sampler Thread B.
7.
Click on Test Plan and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
8.
Save the test plan.
9.
Run the test.
162
Chapter 5 ■ JMeter Test Plan Components
Click on the View Results Tree and select Debug Sampler Thread A. You will notice that UDV_Aplha is
alpha and UDV_Bravo is bravo, as defined initially in the test plan element (see Figure 5-146).
The logs show that the value of UDV_Bravo was set to zulu after the JSR223 post-processor executed.
However, this change is local to Thread Group A and is not propagated to Thread Group B.
Click on the View Results Tree and select Debug Sampler Thread B. You will find that there was no
change to the value of UDV_Bravo (see Figure 5-147).
163
Chapter 5 ■ JMeter Test Plan Components
3.
Click on HTTP Request Defaults and update the Server Name or IP field to
${SERVER} (see Figure 5-149).
55
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_05/properties-and-variables/
UDVUsingCmdLineParamTestPlan.jmx
164
Chapter 5 ■ JMeter Test Plan Components
4.
Save the test plan.
5.
Run the test from the command line. Issue the following command at the CMD prompt:
6.
Open the test results log file. Issue the following command at the CMD prompt:
C:\>cat UDV-cmd-line-test.log
Note that the server name has been passed from the command line. This was propagated to the server
defined under user defined variables. The request samplers referred to this value by enclosing it in ${}.
Similarly, you can configure Number of Threads (Users), Ramp-Up Period (in Seconds), and Loop
Count to simulate different loads based on the environment.
Conclusion
In this chapter, you learned to configure your test plan to enable serial and parallel execution of thread groups
to simulate real users while performing load testing. You used pre-processors by using the HTTP URL Rewriting
Modifier. You learned about Logic Controllers for enabling loops based on conditions, You learned about JMeter
timers and their appropriate use in test scripts for setting up hard delays to replicate actual user scenario etc.,
and the HTTP Request Sampler to configure real-world HTTP requests. You also learned about the Response
Assertion and its various options and how to apply them to responses from samplers and sub-samplers to ensure
that tests are running correctly. You also learned about the usage of assertions results, which are especially suited
for viewing the results of assertions. Listeners like View Results Tree, View Results In Table, and Aggregate Report
Listeners are useful in viewing the results of JMeter test script, saving the test results in CSV and XML formats, and
using non-GUI mode to save results to a file. The Regular Expression Extractor extracts value from the sampler and
stores the value locally for successive samplers. You also learned about the use of JMeter properties, variables, and
user defined variables along with their scope with respect to test plans and thread groups.
In the next chapter, you will learn about distributed testing using JMeter in a master-slave environment,
various modes of sending results from the slaves to the master, and current limitations of distributed testing.
165
CHAPTER 6
Distributed Testing
This chapter discusses how to perform distributed testing using JMeter. We cover the prerequisites and
configuration of JMeter with remote hosts in master/slave environments. You’ll see how to run tests in GUI
as well as non-GUI mode and learn about various ways that JMeter sends information from slave(s) to the
master. Lastly, there is a section that will be useful in troubleshooting exceptions while you are developing
tests script and running in distributed environment.
At the end of this chapter, you’ll have a good idea about the distributed load testing approach using
JMeter. You will be able to set up a distributed testing environment and trigger test scripts from various JMeter
slaves. Those who are already familiar with distributed testing using JMeter can proceed to the next chapter.
When the load generated by JMeter reaches the limit of a client machine in terms of CPU, memory,
or network space, then you need to utilize more than one machine. JMeter can be configured to do
distributed testing.
In a distributed testing environment, each JMeter client is configured to simulate the load of a few
hundred users and the combination of these clients will trigger a few thousand requests simultaneously.
It can be thought of as horizontal scaling of load, as you can increase and simulate the test load by adding
client machines to the testing environment.
Prerequisites
The prerequisites for setting up the distributed testing cluster using JMeter are as follows:
• All the slaves must be on the same subnet as the master.
• The application under target should be on the same subnet.
• All slaves and the master should have the same version of JMeter and JVM.
• The firewall on the master and the slaves should be turned off.
• There should be no antivirus software installed on the master or the slaves.
• The network should be stable.
• There should not be any extraneous network activity on the subnet.
Configuration
Open the jmeter.properties file on the master and add each slave’s hostname or IP address, as shown here:
remote_hosts=192.168.0.7,192.168.0.8
[email protected],user1
[email protected],user2
[email protected],user3
[email protected],user4
[email protected],user5
[email protected],user6
[email protected],user7
[email protected],user8
[email protected],user9
[email protected],user10
Ensure that the users.csv file is placed in the /bin folder of the slave’s $JMETER_HOME directory. When
the test executes, it will be picked up.
Let’s illustrate this with an example.
Follow these steps or download the DistributedTestPlan.jmx1 file:
1.
Create a test plan and give it a meaningful name, such as Distributed Testing.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure Number of Threads (Users) as 1 and Loop Count as 1.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
1
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_06/DistributedTestPlan.jmx
168
Chapter 6 ■ Distributed Testing
4.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Request Defaults. Configure Server Name or IP as <your_machine_ip_or_
hostname> and Port Name as 8080.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Path as /user/signIn and Method as POST.
6.
Click on HTTP Request and go to Edit ➤ Add ➤ Config Element. Add CSV Data
Set Config and configure as shown in Figure 6-1.
7.
Click on HTTP Request again and configure the parameters as shown in Figure 6-2.
8.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
9.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Path as /user/signOut and Method as HEAD.
10.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
169
Chapter 6 ■ Distributed Testing
11.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
12.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results
in Table.
13.
Save the test plan.
170
Chapter 6 ■ Distributed Testing
From the apache-jmeter-3.0/bin directory on each slave, you need to start jmeterserver using the
following command:
C:\>jmeter-server
C:\> jmeter-server
Could not find ApacheJmeter_core.jar ...
... Trying JMETER_HOME=..
Found ApacheJMeter_core.jar
Writing log file to: C:\apache-jmeter-3.0\bin\jmeter-server.log
Created remote object:
UnicastServerRef [liveRef: [endpoint:[192.168.0.7:51324](local),objID:[535e2c0b:
15c0e3a3328:-7fff, 3496195728845345408]]]
C:\> jmeter-server
Could not find ApacheJmeter_core.jar ...
... Trying JMETER_HOME=..
Found ApacheJMeter_core.jar
Writing log file to: C:\apache-jmeter-3.0\bin\jmeter-server.log
Created remote object:
UnicastServerRef [liveRef: [endpoint:[192.168.0.8:63904](local),objID:
[-99f93d6:15c0e3a7148:-7fff, -6488513131611751121]]]
GUI Mode
You have set up two slaves (remote hosts), which are visible on the JMeter GUI. Run the test on one remote
host by selecting Remote Start and selecting any remote host or using the Remote Start All option.
Under Thread Group, you can see that you are running 1 thread and selecting Remote Start All; it will trigger
this test on both remote hosts. The View Results in Table will show four responses, as shown in Figure 6-4.
171
Chapter 6 ■ Distributed Testing
Also on the remote host, the jmeter-server logs will show the test start and the test end.
Remote host #1 jmeter-server logs.
Starting the test on host 192.168.0.7 @ Mon May 15 15:31:15 PDT 2017 (1494887475261)
Finished the test on host 192.168.0.7 @ Mon May 15 15:31:16 PDT 2017 (1494887476397)
Starting the test on host 192.168.0.8 @ Mon May 15 15:31:15 PDT 2017 (1494887475062)
Finished the test on host 192.168.0.8 @ Mon May 15 15:31:15 PDT 2017 (1494887475390)
Non-GUI Mode
GUI mode takes a lot of memory. JMeter provides an option to do a remote run of the tests.
Execute this command with -R and add the remote hosts’ IP addresses.
It will show the following output. You can see that tests are executed on remote engines.
Execute the following command with -r without the remote hosts’ IP addresses. This command will
take the remote hosts from the jmeter.properties file assigned to the remote hosts property.
C:\>jmeter -n -t DistributedTestPlan.jmx -r
RMI Port
By default, the server_port is set to 1099. Sometimes it may be that this port is blocked, and we are not able
to start JMeter in the master-slave environment. In this case, we need to set the server_port of the slaves to
something else.
172
Chapter 6 ■ Distributed Testing
Open the jmeter.properties file on the slaves and change it to a different port number, such as 1234.
# RMI port to be used by the server (must start rmiregistry with same port) server_port=1234
If you forget to use the updated port number in the command, you will get the exception shown here:
#mode=Standard
• Batch Mode: Send saved samples when either the count (num_sample_threshold)
or time (time_threshold) exceeds a threshold, at which point the samples are sent
synchronously. The thresholds can be configured on the server using the following
properties:
num_sample_threshold: The number of samples to accumulate; default is 100
173
Chapter 6 ■ Distributed Testing
#mode=Batch
...
#num_sample_threshold=100
# Value is in milliseconds
#time_threshold=60000
...
• Statistical Mode: Send a summary sample when either the count or time exceeds a
threshold. The samples are summarized by thread group name and sample label.
The following fields are accumulated:
• Elapsed time
• Latency
• Bytes
• Sample count
• Error count
Other fields that vary between samples are lost.
#mode=Statistical
#Set to true to key statistical samples on threadName rather than threadGroup
#key_on_threadname=false
...
#num_sample_threshold=100
# Value is in milliseconds
#time_threshold=60000
...
• Hold Mode: Hold samples in an array until the end of a run. This may use a lot of
memory on the server and is discouraged.
#mode=Hold
• DiskStore Mode: Store samples in a disk file (under java.io.temp) until the end of a
run. The serialized data file is deleted on JVM exit.
# DiskStore: as for Hold mode, but serialises the samples to disk, rather than
saving in memory
#mode=DiskStore
174
Chapter 6 ■ Distributed Testing
#mode=Stripped
#mode=StrippedBatch
• Asynch: Samples are temporarily stored in a local queue. A separate worker thread
sends the samples. This allows the test thread to continue without waiting for the
result to be sent back to the client (the master). However, if samples are being
created faster than they can be sent, the queue will eventually fill up, and the
sampler thread will block until some samples can be drained from the queue. This
mode is useful for smoothing out peaks in sample generation. The queue size can be
adjusted by setting the JMeter property asynch.batch.queue.size (default 100)
on the server node.
• Custom Implementation Mode: Set the mode parameter to custom sample sender
class name. This must implement the interface SampleSender and have a constructor
that takes a single parameter of type RemoteSampleListener.
#mode=org.example.load.MySampleSender
Open the jmeter.properties file and set the mode as per the requirements.
175
Chapter 6 ■ Distributed Testing
In the first case, when the remote hosts are still booting up, JMeter has a property to wait for some time
and then trigger the test. You can set how many retries JMeter has to make and how much retry delay it has
to wait before starting the test.
By default, client.tries is set to 1 and client.retries_delay is set to 5000 milliseconds.
Uncomment these properties and rerun the test.
# If there are initialization retries, the following property sets a delay between attempts
client.retries_delay=5000
JMeter has a property to skip the remote hosts if they are not reachable and continue the test with the rest.
Update client.continue_on_fail to true under the jmeter.properties file.
# When all initialization tries are made, test will fail if some remote engines are failed
# Set the following property to true to ignore failed nodes and proceed with test
client.continue_on_fail=true
Run the test again and it will skip the unreachable host.
176
Chapter 6 ■ Distributed Testing
Limitations
The limitations with JMeter in distributed testing are listed here:
• It is quite expensive to set up dedicated hardware for performance testing on the
premises. A cloud-based distributed testing environment will provide a solution to
this limitation.
• RMI cannot communicate across subnets without a proxy; therefore, neither
can JMeter.
• Since JMeter sends all the test results to the controlling console, it is easy to saturate
the network. It is a good idea to use the Simple Data Writer to save the results and
view the file later with one of the graph Listeners.
• A single JMeter client running on a 2-3 GHz CPU can handle 300-600 threads
depending on the type of test. (The exception is the web-services). XML processing
is CPU intensive and will rapidly consume all the CPU cycles. As a general rule,
performance of XML-centric applications is 4-10 times slower than applications
using binary protocols.
Conclusion
In this chapter, you learned to distribute load generation by using multiple machines, configuring remote
hosts, and verifying that the remote hosts have successfully run the test. You also learned about the
limitations of distributed testing using JMeter. In the next chapter, you will learn JMeter best practices that
will make you a more efficient user of JMeter.
177
CHAPTER 7
This chapter has examples, each illustrating a concept, feature, or a best practice of JMeter.
At the end of this chapter, you’ll have more insight into JMeter and understand little efficient techniques
that will help you write better and faster tests. It is not mandatory to read through this chapter, and if you
want to skip to next chapter, you can do so.
Follow Redirects
Always enable the Follow Redirects option.
When you browse web sites or are using a web application, sometimes the browser redirects to a new
URL using the concept of URL redirection. This is also called URL forwarding. HTTP status codes 3XX are
used to indicate redirection.
When you add an HTTP Request Sampler to the test plan, the Follow Redirects flag is enabled by default.
You will see what happens when this flag is not checked in the following example.
Follow these steps or download FollowRedirectTestPlan.jmx.1
1.
Create a test plan and give it a meaningful name, such as Follow Redirect Test.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as
/dt/info. Uncheck the Follow Redirects checkbox.
4.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
1
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_07/FollowRedirectTestPlan.jmx
180
Chapter 7 ■ JMeter Best Practices
5.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree
(see Figure 7-2).
6.
Save the test plan.
7.
Run the test.
The results will be similar to those shown in Figure 7-3.
181
Chapter 7 ■ JMeter Best Practices
Observe the sampler results shown in Figure 7-4. The assertion failed as the response code was 302
instead of 200. Also note that the Location field in the Response Headers indicates the correct URL to be
http://localhost:8080/dt/newInfo.
Of course, the test will succeed when you select the Follow Redirects flag in the HTTP Request Sampler.
■■Note It is a best practice to select the Follow Redirects flag. Also, it is equally important to add assertions
during test script development to make sure that we detect the failures.
Cookie Manager
Always use a cookie manager, as cookies are the most common mechanism for web applications to maintain
session state.
Consider the following use-case for placing an order from the Digital Toys Inc. web application.
1.
Sign in (user [email protected], password user1).
2.
Check Detail.
3.
Choose Add To Cart.
4.
Check out.
5.
Add the billing/shipping address.
6.
Add the credit card details.
182
Chapter 7 ■ JMeter Best Practices
7.
Place your order.
8.
View the order history.
9.
Sign out.
One of the best features of JMeter is the HTTP(S) Test Script Recorder. Let’s use it to record this use-case
by following these steps or downloading CookieManagerTestPlan.jmx.2
1.
Create a test plan and give it a meaningful name, such as Cookie Manager Test.
2.
Click on WorkBench and go to Edit ➤ Add ➤ Non-Test Elements. Add HTTP(S)
Test Script Recorder. Choose Global Settings and then configure Port as 7070,
Test Plan Content, Target Controller as WorkBench > HTTP(S) Test Script
Recorder, and URL Patterns to Exclude as .*\.(css|js|ico|ttf|woff).\*
3.
Click on the Start button.
4.
Use the browser and follow the use-case steps to place an order on the Digital
Toys web application.
5.
Click on test plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
6.
Select all recorded browser actions from WorkBench, and then drag and add
them as child elements of Thread Group.
7.
Save the test plan.
8.
Run the test.
9.
Log in to the Digital Toys Inc. web application and verify the order (see Figure 7-5).
2
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_07/CookieManagerTestPlan.jmx
183
Chapter 7 ■ JMeter Best Practices
The process of recording the use-case created an order. After that, the JMeter test execution should have
created another order. However, looking under Order History, we only find one order. Why is the second
order missing? The JMeter test execution was not successful in placing an order because the session was not
maintained between requests. Let’s fix this by adding an HTTP Cookie Manager.
1.
Now click on test plan and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
2.
Run the test.
3.
Log in to the Digital Toys Inc. web application and verify the order (see Figure 7-6).
4.
Go to Order History under the Digital Toys Inc. web application and verify the
recently placed order. You will see that there were two orders placed.
■■Note It is a best practice to always use an HTTP Cookie Manager. It should be a child element of Thread
Group, as this will ensure that each thread is uniquely identified by the server.
184
Chapter 7 ■ JMeter Best Practices
Cache Manager
The Cache Manager simulates a browser cache. You can make JMeter behave closer to a real browser by
including an HTTP Cache Manager.
JMeter is not a real browser. It does not execute JavaScript or render content. A typical web page has many
media files, such as images, video, audio, and script files. A good web page design includes headers that tell the
proxy servers and browsers to cache these resources so that they are downloaded from the origin the first time
and later fetched from the cache. The HTTP Cache Manager, if included, will cache the cache-able resources.
Each thread has its own cache and you can specify the limit on the cache size by configuring the Max
Number of Resources to Cache field. Setting this value too high will increase the memory required by JMeter
(see Figure 7-7).
<build>
<plugins>
<plugin>
<groupId>com.lazerycode.jmeter</groupId>
<artifactId>jmeter-maven-plugin</artifactId>
<version>1.10.1</version>
<executions>
<execution>
<id>jmeter-tests</id>
<phase>verify</phase>
<goals>
<goal>jmeter</goal>
</goals>
3
https://github.com/Apress/pro-apache-jmeter/tree/master/Matam_Ch_07/jmeter-mvn-example
185
Chapter 7 ■ JMeter Best Practices
</execution>
</executions>
</plugin>
</plugins>
</build>
Issue the following command in the CMD prompt to run the JMeter test.
c:\>mvn verify
186
Chapter 7 ■ JMeter Best Practices
[debug] JMeter is called with the following command line arguments: -n -t c:\github\jmeter-
mvn-example\src\test\jmeter\GoogleSearch.jmx -l c
:\github\jmeter-mvn-example\target\jmeter\results\20170515-GoogleSearch.jtl -d c:\github\
jmeter-mvn-example\target\jmeter -j c:\github\jmete
r-mvn-example\target\jmeter\logs\GoogleSearch.jmx.log
[info] Executing test: GoogleSearch.jmx
[debug] Creating summariser <summary>
[debug] Created the tree successfully using c:\github\jmeter-mvn-example\src\test\jmeter\
GoogleSearch.jmx
[debug] Starting the test @ Mon May 15 22:17:42 PDT 2017 (1494911862824)
[debug] Waiting for possible shutdown message on port 4445
[debug] summary = 1 in 1.2s = 0.8/s Avg: 440 Min: 440 Max: 440 Err: 0 (0.00%)
[debug] Tidying up ... @ Mon May 15 22:17:44 PDT 2017 (1494911864099)
[debug] ... end of run
[info] Completed Test: GoogleSearch.jmx
[INFO]
[INFO] Test Results:
[INFO]
[INFO] Tests Run: 1, Failures: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.905 s
[INFO] Finished at: 2017-05-15T22:17:44-07:00
[INFO] Final Memory: 18M/223M
[INFO] ------------------------------------------------------------------------
4
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_07/PassingVariableTestPlan.jmx
187
Chapter 7 ■ JMeter Best Practices
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure the name as Thread Group A.
3.
Click on Thread Group A and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as /.
4.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
5.
Click on the HTTP Request of Thread Group A and go to Edit ➤ Add ➤ Post
Processor. Add Regular Expression Extractor. Configure Reference Name as url,
Regular Expression as http:\/\/(.\*):8080\/, Template as $1$, Match No.(0
for Random) as 1, and Default Value as NONE (see Figure 7-9).
188
Chapter 7 ■ JMeter Best Practices
6.
Click on HTTP Request of Thread Group A and go to Edit ➤ Add ➤ Post
Processor. Add BeanShell PostProcessor. Add this code to the Script text area:
${__setProperty(url, ${url})}. See Figure 7-10.
7.
Click again on the test plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread
Group. Configure the name as Thread Group B.
8.
Click on Thread Group B and go to Edit ➤ Add ➤ Sampler and add HTTP
Request. Configure Server Name or IP as ${__property(url)}, Port Number as
8080, and Path as / (see Figure 7-11).
189
Chapter 7 ■ JMeter Best Practices
9.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
10.
Click on test plan and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
11.
Save the test plan.
12.
Run the test.
Results are shown in Figure 7-12.
The regular expression extractor extracts the URL and sets the URL variable, which is used by the
BeanShell PostProcessor to define an URL property. The URL property is accessible to the Thread Group B
and is de-referenced in the server or IP parameter of the HTTP request. You can see that URL variable has
been replaced by the actual value in the second Thread Group B.
190
Chapter 7 ■ JMeter Best Practices
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure the name as Thread Group 1 and the Number of Threads (Users) as 5.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as /dt,
and Name as Sampler 1.
4.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
Configure Name as Thread Group 2 and Number of Threads (users) as 5.
5.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as /dt,
and Name as Sampler 2.
5
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_07/ParallelThreadGroupTestPlan.jmx
191
Chapter 7 ■ JMeter Best Practices
6.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
7.
Save the test plan.
8.
Run the test.
The results are shown in Figure 7-14.
You can conclude that the thread groups have executed in parallel, as the web requests for Sampler 1
have been intermixed with requests for Sampler 2.
6
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_07/CSVDataSetConfigTestPlan.jmx
192
Chapter 7 ■ JMeter Best Practices
3.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, Path as
/user/signIn, and Method as POST.
4.
Click on HTTP Request and go to Edit ➤ Add ➤ Config Element. Add CSV
Data Set Config. Configure Filename as users.csv, Variable Names (comma-
delimited) as username,password, Delimiter as, (see Figure 7-15).
5.
Click on HTTP Request and configure Send Parameters with the Request, as
shown in Figure 7-16.
6.
Add the users.csv file to the same folder with these contents: user1@
dt.com,user1 [email protected],user2 [email protected],user3 [email protected],user4
[email protected],user5.
7.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
193
Chapter 7 ■ JMeter Best Practices
8.
Save the test plan.
9.
Run the test.
The results will be similar to those shown in Figure 7-17.
Customizing Properties
JMeter can be customized by configuring various properties. By default, these are loaded from the jmeter.
properties file. These can be overridden by a custom properties file.
It is a best practice to use your own custom properties file instead of modifying the jmeter.properties
file. The custom properties file can be specified by modifying the user.properties property in the jmeter.
properties file. By default, this property is set to user.properties.
The following snippet shows the custom properties being loaded from the my.properties file.
File: jmeter.properties
# Should JMeter automatically load additional JMeter properties? # File name to look for
(comment to disable) user.properties=my.properties
194
Chapter 8 ■ Troubleshooting JMeter
The string is admin:admin because the username and password are admin.
2.
Add a header with the name of Authorization and a value of BASIC
YWRtaW46YWRtaW4=, where YWRtaW46YWRtaW4= is the Base64-encoding obtained
from the previous step (see Figure 8-4).
3
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_08/HeaderManagerTestPlan.jmx
205
Chapter 8 ■ Troubleshooting JMeter
3.
Run the JMeter test. It should be able to authenticate successfully.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and Path as
/admin.
5.
Click on HTTP Request and go to Edit ➤ Add ➤ Assertions. Add Response
Assertion. Configure Response Field to Test as Response Code, Pattern
Matching Rules as Equals, and Patterns To Test as 200.
6.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
7.
Save the test plan.
Run the JMeter test. It should be able to authenticate successfully.
4
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_08/AuthorizationManagerTestPlan.jmx
206
Chapter 8 ■ Troubleshooting JMeter
5
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_08/ThreadGroupValidateTestPlan.jmx
207
Chapter 8 ■ Troubleshooting JMeter
8.
Click on View Results Tree. You will observe that the test has been executed with
a single thread even though it was configured with 10 threads.
There are two more options introduced with JMeter 3.0; Start and Start No Pause. These two options
provide a shortcut to execute threads individually. The only difference between these two menu options is
that with the latter, Timer if Configured in the thread group are skipped and the thread will run without any
manual pauses.
These two options are useful when the test has multiple thread groups and you are still refining it. You
can use these options to verify individual thread groups selectively.
208
Chapter 8 ■ Troubleshooting JMeter
You can monitor the memory and CPU usage of JMeter using JVisualVM. This tool is shipped with the
JDK installation, by default.
The JVisualVM screen shown in Figure 8-7 shows excessive CPU and memory usage by JMeter.
To increase the HEAP memory for JMeter, specify it using the JVM_ARGS environment variable before
starting JMeter. Enter this command in CMD prompt:
Conclusion
In this chapter, you learned to troubleshoot various common errors while working with JMeter test scripts.
In the next chapter, you will learn about JMeter plugins and learn how to use them in your test plan for
monitoring and generating good looking reports.
210
CHAPTER 9
JMeter Plugins
This chapter introduces JMeter plugins, which are developed as a part of Google Code (JP@GC). They are
useful in analyzing performance test results and displaying beautiful graphs. We will illustrate the use of
PerfMon and jp@gc, the PerfMon Metrics Collector, with the help of an example.
At the end of this chapter, you will understand JMeter plugins, including how to install them and use
them in test plans. You will also able to develop and run test plans and export monitoring reports. Those
who are already familiar with JMeter plugins can proceed to the next chapter.
Although JMeter generates very useful performance metrics, it does not have good visualizers and visually
appealing graphs. JMeter Plugins at Google Code (JP@GC) closes this gap and offers several plugins that
generate elegant graphs which help you visualize the performance test results. Additionally, JP@GC provides
plugins that extend JMeter functionality with new config elements, timers, pre-processor,
post-processor, assertions, listeners, and logic controllers.
For more details, look at JP@GC Standard Documentation.1
Each JP@GC plugin has a Help on This Plugin link, which navigates to the Wiki page.2 It also has an
active community. You can also contact the people on the forum on the Mailing List.3
Each JP@GC plugin provides a rich set of options to customize the generation of pleasing graphs to
meet a variety of needs.
PerfMon
During performance testing, it is important to know the health of the servers hosting the web application
under test. To address this, the PerfMon package supports server/cluster monitoring. Using this, you can
monitor CPU, memory, swap, disk I/O, and network performance on all platforms. See Figure 9-1.
1
http://jmeter-plugins.org/wiki/Start/
2
http://jmeter-plugins.org/wiki
3
https://groups.google.com/forum/#!forum/jmeter-plugins
C:\ServerAgent-2.2.1>dir
Volume in drive C has no label.
Volume Serial Number is DA32-01EE
Directory of C:\ServerAgent-2.2.1
05/15/2017 10:36 PM <DIR> .
05/15/2017 10:36 PM <DIR> ..
4
http://jmeter-plugins.org/downloads/file/ServerAgent-2.2.1.zip
212
Chapter 9 ■ JMeter Plugins
C:\ServerAgent-2.2.1>
C:\ServerAgent-2.2.1>type startAgent.bat
@echo off
java -jar %0\..\CMDRunner.jar --tool PerfMonAgent %*
C:\ServerAgent-2.2.1>startAgent.bat
INFO 2017-05-15 22:40:13.101 [kg.apc.p] (): Binding UDP to 4444
INFO 2017-05-15 22:40:14.099 [kg.apc.p] (): Binding TCP to 4444
INFO 2017-05-15 22:40:14.101 [kg.apc.p] (): JP@GC Agent v2.2.0 started
By default, it opens UDP and TCP connections on port 4444, which are used to connect to JMeter to
collect metrics. Console output indicates that the JP@GC server agent has been started successfully.
To start the server agent on a different port, specify the same on the command line.
The command-line options are --udp-port and --tcp-port.
In the logs, you can see that UDP is bound to port 1234 and TCP is bound to 1235.
To stop the server agent, use this command:
C:\ServerAgent-2.2.1>startAgent.bat --auto-shutdown
C:\ServerAgent-2.2.1>startAgent.bat --sysinfo
INFO 2017-05-15 22:45:09.385 [kg.apc.p] (): *** Logging available processes ***
INFO 2017-05-15 22:45:09.475 [kg.apc.p] (): Process: pid=2080 name=taskhost.exe
args=taskhost.exe
INFO 2017-05-15 22:45:09.477 [kg.apc.p] (): Process: pid=8980 name=dwm.exe
args=C:\Windows\system32\Dwm.exe
INFO 2017-05-15 22:45:09.478 [kg.apc.p] (): Process: pid=7572 name=explorer.exe
args=C:\Windows\Explorer.EXE
213
Chapter 9 ■ JMeter Plugins
You can use --loglevel parameter to set the level of logging. The log levels available are INFO, ERROR,
WARNING, and DEBUG.
You can download JMeter standard plugins from the JMeter Plugins web page.5
Extract the plugin into the apache-jmeter-3.0 root folder and execute the command as given. You will
find the latest extracted files, as shown here.
c:\apache-jmeter-3.0\lib\ext>dir /O:-D
Volume in drive C has no label.
Volume Serial Number is DA32-01EE
Directory of c:\apache-jmeter-3.0\lib\ext
.
.
.
05/14/2016 11:47 AM 106 readme.txt
10/12/2015 10:07 AM <DIR> ..
10/12/2015 10:07 AM <DIR> .
10/12/2015 10:07 AM 10,782 CMDRunner.jar
10/12/2015 10:07 AM 1,262,178 JMeterPlugins-Standard.jar
06/17/2015 09:47 AM 95 JMeterPluginsCMD.sh
06/17/2015 09:47 AM 68 TestPlanCheck.bat
06/17/2015 09:47 AM 100 TestPlanCheck.sh
06/17/2015 09:47 AM 63 JMeterPluginsCMD.bat
22 File(s) 4,387,697 bytes
2 Dir(s) 7,541,547,008 bytes free
c:\apache-jmeter-3.0\lib\ext>
5
http://jmeter-plugins.org/downloads/file/JMeterPlugins-Standard-1.3.1.zip
214
Chapter 9 ■ JMeter Plugins
6
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_09/PerfMonPluginTestPlan.jmx
215
Chapter 9 ■ JMeter Plugins
10.
Click on jp@gc - PerfMon Metrics Collector. Configure Servers To Monitor by
clicking the Add Row button. Configure HOST/ IP as localhost, Port as 4444,
and Metric to Collect as CPU (change it to meet your requirements).
11.
Click again on the Add Row button to set Metric to Collect for Memory.
12.
Save the test plan.
13.
Start the server agent if it was not started earlier.
14.
Run the test.
The results will be similar to those shown in Figure 9-3.
216
Chapter 9 ■ JMeter Plugins
To save the results as a graph, right-click on the graph and choose a suitable option (see Figure 9-4).
If you want to monitor different metrics on the same host/IP, click on Copy Row and change the Metric
to Collect parameter. Available metrics are CPU, Memory, Swap, Disk I/O, Network I/O, TCP, JMX, EXEC,
and TAIL. The Metric parameter can be used to set the CPU parameter per scope. Double-click on the cell,
click on the three dots on the right side to open a new pop-up window. From that window, you can control
the appearance of graphs. Mouse over to see the help text.
Figure 9-5 details the kind of metrics that can be collected for CPU.
217
Chapter 9 ■ JMeter Plugins
Non-GUI Mode
JMeter properties can also be used to configure the PerfMon plugin. To do this, add the following properties
to the jmeter.properties file.
• jmeterPlugin.perfmon.interval: Metrics collection interval in milliseconds.
• jmeterPlugin.perfmon.useUDP: Set to true/false. Enabling this will make JMeter try
a UDP connection if the TCP connection attempts fail.
• jmeterPlugin.perfmon.label.useHostname: Set to true/false. Enables using “short”
hostnames. The default pattern is ([\w\-]+)\..*
• jmeterPlugin.perfmon.label.useHostname.pattern: String (escaped), regular
expression to extract hostname (first group is matched). ° For example, the default pattern
would be: jmeterPlugin.perfmon.label.useHostname.pattern=([\w\-]+)\..*
• Pattern for EC2 us-east/west subdomain matching is as follows: jmeterPlugin.
perfmon.label.useHostname.pattern=([\w\-]+\.us-(east|west)-[0-9]).*
• forcePerfmonFile: Set to true/false. Enabling it forces JMeter to write a JTL file with
PerfMon metrics in the current directory.
218
Chapter 9 ■ JMeter Plugins
Run JMeter in non-GUI mode. Configure the filename to save the monitoring results too. Later, you can
load the saved file into the GUI and review the timeline.
Conclusion
In this chapter, you learned about JMeter Plugins at Google Code (JP@GC) and explored various options
for the jp@gc - PerfMon Metrics Collector. In the next chapter, you will learn about the advanced concepts
of JMeter, which we call the JMeter recipes. These will be useful while performance testing a database/FTP/
REST API/mobile web application.
219
CHAPTER 10
JMeter Recipes
This chapter explains advanced JMeter features like using JDBC, FTP, REST/JSON, AJAX, mobile web
applications, and SOAP-XML performance testing, which will help you achieve specialized performance
testing needs.
At the end of this chapter, you will have a good idea of a few advanced JMeter features and should be
able to use these features to develop test scripts. Those who are already familiar with these features can
proceed to the next chapter.
Install MySQL
MySQL is a leading open source database server. Download and install the community server edition.1
Follow the instructions on the web site to start the server.2 Create a user and note the username and
password. It is good to set the \bin folder in the standard path variable to access it from any directory.
C:\mysql-5.6.36-winx64\bin>msysqld
The previous command will start the mysql server. Use the following command to log in as the root.
C:\mysql-5.6.36-win64\bin>mysql -u root
mysql> create user "jmeter_user"@"localhost" identified by "mypass";
Query OK, 0 rows affected (0.00 sec)
mysql>
For this example, we will use Employees DB, which is a database that contains a large amount of data
(approximately 160MB) spread over six separate tables and consisting of 4 million records in total. The
documentation for this database is available on the MySQL web site.3
1
https://dev.mysql.com/downloads/mysql/5.6.html#downloads
2
https://dev.mysql.com/doc/refman/5.7/en/windows-start-command-line.html
3
https://dev.mysql.com/doc/employee/en/
+-----------------------------+
| INFO |
+-----------------------------+
| CREATING DATABASE STRUCTURE |
+-----------------------------+
+------------------------+
| INFO |
+------------------------+
| storage engine: InnoDB |
+------------------------+
+---------------------+
| INFO |
+---------------------+
| LOADING departments |
+---------------------+
+-------------------+
| INFO |
+-------------------+
| LOADING employees |
+-------------------+
+------------------+
| INFO |
+------------------+
| LOADING dept_emp |
+------------------+
+----------------------+
| INFO |
+----------------------+
| LOADING dept_manager |
+----------------------+
+----------------+
| INFO |
+----------------+
| LOADING titles |
+----------------+
+------------------+
| INFO |
+------------------+
| LOADING salaries |
+------------------+
C:\employees_db>
4
https://launchpad.net/test-db/employees-db-1/1.0.6/+download/employees_db-full-1.0.6.tar.bz2
222
Chapter 10 ■ JMeter Recipes
C:\>mysql -u root;
Mysql> use employees;
mysql> select count(*) from employees;
+----------+
| count(*) |
+----------+
| 300024 |
+----------+
1 row in set (0.16 sec)
If you see this previous output, you have set up the database correctly.
The schema of the database is shown in Figure 10-1.
223
Chapter 10 ■ JMeter Recipes
5
http://dev.mysql.com/downloads/connector/j/
6
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_10/JDBCTestPlan.jmx
224
Chapter 10 ■ JMeter Recipes
4.
Click on Thread Group and go to Edit ➤ Add ➤ Samplers to add JDBC Request.
Configure it with the Variable Name Bound to the Pool option set to jdbcConfig
(this is the same value as configured in the JDBC Connection Configuration).
Configure Query as select count (*) from employee where first_name
like 'Ge%' (see Figure 10-3).
5.
Run the test.
Results will be similar to those shown in the following figures.
225
Chapter 10 ■ JMeter Recipes
Check the JDBC request that JMeter sent to MySQL (see Figure 10-5).
226
Chapter 10 ■ JMeter Recipes
Check the response data for the JDBC request (see Figure 10-6).
■■Tip FTP is commonly available, but it is considered insecure. Use SFTP instead.
Follow these steps to set up the FTP if it’s not set up already.
1.
Click on the Control Panel, then choose Programs and Features ➤ Turn Windows
features on or off (left side). Select the Internet Information Service and select
FTP Server, Web Management Tools, and World Wide Web Services. Click OK.
2.
Click on the Control Panel, then choose ➤ Administrative Tools ➤ Internet
Information Services (IIS) Manager. Right-click on the sites and then choose Add
FTP Site.
Fill in the details. You are done setting up the FTP server locally.
3.
Open your browser and launch ftp://<your_ip_address> enter
user/password. You can see the local mapped folder files on the browser.
If you are MacOS user, to start the FTP server, enter the following command in the terminal window.
■■Note Be sure to shut down your FTP server after use for security reasons.
Let’s look at an example to illustrate the performance testing of a FTP server. In this example, we will
use JMeter to connect to the FTP server and transfer a file from the server. The file is an image named
cormorant.jpg, so the transfer should use binary mode.
Follow these steps or download FTPTestPlan.jmx.7
1.
Create a test plan and give it a meaningful name, such as FTP Test Plan.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (users). Add Thread Group.
Configure Number of Threads (Users) as 1 and Loop Count as 5000.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element ➤ FTP Request
Defaults. Add FTP Request Defaults. Configure the Server Name or IP as
localhost (see Figure 10-8).
7
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_10/FTPTestPlan.jmx
228
Chapter 10 ■ JMeter Recipes
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add FTP Request.
Configure the username and password. Set the value of the Remote File as /ftp.
jpg and Local File as C:\temp\ftp.jpg. Since this is an image file, enable the
Use Binary mode checkbox (see Figure 10-9).
5.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add Graph Result.
6.
Run the test.
Results will be similar to those shown in Figure 10-10.
229
Chapter 10 ■ JMeter Recipes
8
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
230
Chapter 10 ■ JMeter Recipes
Now let’s look at the REST API for Create, Read, Update, and Delete (CRUD) operations. The API uses
the HTTP verbs:
• POST: Creates the book with a JSON payload
• GET: Reads the book given the ID
• PUT: Updates the book with a JSON payload
• DELETE: Deletes the book given the ID
Let’s illustrate the Create operation through an example.
Follow these steps or download RESTJSONTestPlan.jmx.9
1.
Create a test plan and give it a meaningful name, such as REST Create Book
Test Plan.
2.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Configuration Element. Add
HTTP Header Manager. Configure the Headers Stored in the Header Manager,
Name as Content-Type and Value as application/json. Add another header
with Name set to Accept and Value set to application/json (see Figure 10-11).
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request
Sampler. Configure Server Name or IP as localhost, Port Number as 8080,
Implementation as HttpClient4, Method as POST, and Path as /books. Click on
the body data and use the following JSON payload. It has required attributes for
the Create operation. The ID has not been specified and it will be assigned when
the book gets created (see Figure 10-12).
{
"title": "The Zen Book",
"countryOfPublication": "Japan",
"publishedBy": "Good Books Inc.",
"author": "Kobayashi"
}
9
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_10/RESTJSONTestPlan.jmx
231
Chapter 10 ■ JMeter Recipes
5.
Click on Thread Group and go to Edit ➤ Add ➤ Listener to add View Results
Tree.
6.
Run the test.
Results will be similar to those shown in Figure 10-13.
Observe that the response has an ID attribute that was assigned by the server.
232
Chapter 10 ■ JMeter Recipes
Unlike the browser, JMeter does not execute JavaScript or render HTML. Testing AJAX is similar to any
other web test. The key is to find all the AJAX requests and their expected responses. You can use the help of
these tools/utilities/plugins:
• Firebug on Firefox10
• HttpWatch on Internet Explorer11
• Developer tools in Chrome12
We use Chrome developer tools to illustrate. You can open the DevTools one of the following ways:
1.
Select the Chrome menu at the top-right of your browser window, and then
select Tools ➤ Developer Tools.
2.
Right-click on any page element and select Inspect Element.
3.
Press Ctrl+Shift+I (or Cmd+Opt+I on the Mac) to open DevTools.
The DevTools window will open at the bottom of your Chrome browser. Select the Network tab. Further,
refine the selection by choosing only AJAX (XHR) requests. The AJAX request URLs are displayed on the left panel.
When you click on a specific AJAX request URL, its request and response details are shown in the panel to the right.
Now you have the AJAX requests and responses to model your JMeter test, as shown in Figure 10-14.
10
http://getfirebug.com
11
https://www.httpwatch.com
12
https://developers.google.com/web/tools/chrome-devtools/
233
Chapter 10 ■ JMeter Recipes
13
http://www.useragentstring.com/pages/useragentstring.php
234
Chapter 10 ■ JMeter Recipes
The JMeter property file jmeter.properties has these two properties that you can configure.
httpclient.socket.http.cps=0
httpclient.socket.https.cps=0
14
Credit: Antonio Gomes Rodrigues
235
Chapter 10 ■ JMeter Recipes
6.
Click on the Save option. Run the application on your mobile device. Its requests
will be recorded in JMeter.
236
Chapter 10 ■ JMeter Recipes
4.
Set the Server value to your computer’s IP address and the Port value to 8080.
5.
Click on the Save option. Run the application on your mobile device. Its requests
will be recorded in Jmeter, as shown in Figure 10-17.
15
https://www.w3.org/TR/#tr_SOAP
237
Chapter 10 ■ JMeter Recipes
Install SOAPUI
SoapUI is a free and open source functional testing tool with very good support for SOAP. Download the
SoapUI package and then follow these steps to create a new project.16
1.
Go to File ➤ New to create a new project. Choose the Description File and
specify the value as Initial WSDL and URL as http://localhost:8080/
services/CurrencyService?WSDL. Enable the Create Sample Requests for
All Operations checkbox to automatically generate sample SOAP requests
(see Figure 10-18).
16
http://www.soapui.org
238
Chapter 10 ■ JMeter Recipes
2.
Double-click on Request1 to open the request template on the pane to the right
(see Figure 10-19).
3.
Fill in the XML arguments. Set arg0 to USD and arg1 to JPY (see Figure 10-20).
239
Chapter 10 ■ JMeter Recipes
4.
Click the green arrow to submit. You should see the response shown in
Figure 10-21.
17
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_10/SOAPTestPlan.jmx
240
Chapter 10 ■ JMeter Recipes
3.
Click on Thread Group and go to Edit ➤ Add ➤ Configuration Element to add
HTTP Header Manager. Configure Headers Stored in the Header Manager,
Name as Content-Type and Value as text/xml (see Figure 10-23).
4.
Click on Thread Group and go to Edit ➤ Add ➤ Sampler. Add HTTP Request.
Configure Server Name or IP as localhost, Port Number as 8080, and
Path as /services/CurrencyService. Copy the SOAP Request XML, which was
generated by the SoapUI earlier, into the body data area (see Figure 10-24).
241
Chapter 10 ■ JMeter Recipes
5.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
6.
Run the test.
The results are shown in Figure 10-25.
Conclusion
In this chapter, we learned about the advanced features of JMeter. We learned about JDBC, FTP, and REST/
JSON testing using their specific samplers and SOAP performance testing using the HTTP Request Sampler.
We also learned about AJAX request performance testing as well as mobile web application performance
testing. In the next chapter, we will go through a case study where we will be learning to apply JMeter skills
that we learned in this and previous chapters to deal with a real-life performance testing project.
242
CHAPTER 11
This chapter presents a case study of a hypothetical e-commerce company called Digital Toys Inc. In the
process, we walk you through various human, financial, and technical dynamics that revolve around web
application performance.
At the end of this chapter, you will gain enough insights about performance test planning and execution
to be of help in your projects. It is good to go through this chapter regardless of your previous experience, as
it talks about performance testing the project.
“If an e-commerce site is making $100,000 per day, a 1-second page delay could cost $2.5
million in lost sales a year.”
—Kissmetrics Blog1
It was clear that they needed to improve the web site’s performance. Martin, the CEO, entrusted this
matter to the Director of Engineering, who in turn delegated it to Alex, one of their best engineers.
1
Source: Sean Work, Minister of Propaganda at Kissmetrics, https://blog.kissmetrics.com/loading-time/
Performance Goals
Alex obtained the response time of the competitors using Alexa.Com2 and compared the results with
WebPageTest.Org.3 He obtained additional performance metrics of the competitors from WebPageTest.Org.
Alex also referred to the report prepared by Insight Management Consultants Inc. Putting it all together, Alex
established the performance goals shown in Table 11-1.
2
http://www.alexa.com
3
http://www.webpagetest.org
244
Chapter 11 ■ Case Study: Digital Toys Inc.
1.
User Lands on the Home Page and Browses the Products (Table 11-2)
No. Step
1 Home Page
2 Browse Products
2.
User Registration (Table 11-3)
No. Step
1 Home Page
2 Sign Up
3 Submit the Registration Form
4 Log Out
3.
User Places an Order for the First Time (Table 11-4)
No. Step
1 Home Page
2 Login Page
3 Index/Product Catalog Page
4 Details
5 Add To Cart
6 Check Out
7 Billing/Shipping Address
8 Credit Card Entry
9 Place Order
10 Order History
11 Sign Out
245
Chapter 11 ■ Case Study: Digital Toys Inc.
4.
User Places an Order for the Second Time (Table 11-5)
No. Step
1 Home Page
2 Login Page
3 Index/Product Catalog Page
4 Details
5 Add To Cart
6 Check Out
7 Place Order
8 Order History
9 Sign Out
5.
User Edits the Billing/Shipping Address (Table 11-6)
No. Step
1 Home Page
2 Login Page
3 Index/Product Catalog Page
4 Billing/Shipping Address
5 Sign Out
6.
User Edits the Payment Information (Table 11-7)
No. Step
1 Home Page
2 Login Page
3 Index/Product Catalog Page
4 Add Credit Card Details
5 Sign Out
246
Chapter 11 ■ Case Study: Digital Toys Inc.
7.
User Uses the Continue Shopping Option (Table 11-8)
No. Step
1 Home Page
2 Login Page
3 Index/Product Catalog Page
4 Details
5 Add To Cart
6 Continue Shopping
7 Check Out
8 Billing/Shipping Address
9 Credit Card Details
10 Place Order
11 Order History
12 Sign Out
■■Note Write the test cases in plain English. This can serve as a requirement for creating a performance test
plan and it is easy to get feedback from other team members.
Tool Selection
Alex searched the Internet and found many performance testing tools. He shortlisted two tools that he felt
would solve the problem. They needed the team to learn a proprietary scripting language.
Alex discussed these two tools with Bob, his manager. Bob appreciated Alex for his efforts but informed
him that there was no budget. Further, the problem needed to be solved in a couple of days and there was no
time for training. Bob asked Alex to be creative.
Alex discovered Apache JMeter.4 He soon found out that JMeter is a time-tested, robust tool for
performance testing. JMeter does not require coding in any scripting language. It is an open source tool and
it is accepted very well in the performance testing community.
■■Note Use a robust tool with good community support that meets your needs and has a short learning curve.
Test Environment
Later, Alex requested Bob for performance test infrastructure. Bob replied that it would take at least three
weeks to procure new hardware and to provision it. Besides, they did not have the budget. Bob asked Alex to
investigate if he could repurpose the existing functional testing infrastructure to set up the performance test
environment.
Alex was happy that all he had to do was to install JMeter on these servers; everything was already there.
4
http://jmeter.apache.org/
247
Chapter 11 ■ Case Study: Digital Toys Inc.
■■Tip In the test environment, obfuscate the production data to prevent exposing critical data like credit card
information and other personal data.
Variable Result
The count of users who are 100,000
logged in at one point in time.
The use-case and the Browsing catalog: 10%
percentage of users. Ordering first time: 60%
Ordering second time: 10%
Changing address: 5%
Changing payment information: 5%
Continue shopping: 10%
Time of day and duration. Most of the users use the application during early morning and at the end
of the day. The duration of load is between 1 to 2 hours.
Critical days of application Five days prior to Christmas.
usage.
248
Chapter 11 ■ Case Study: Digital Toys Inc.
■■Tip Express the usage in terms of percentages. This makes it easier to perform the test with various
counts of simulated users.
Application Build
Alex used the mock payment gateway, which was originally intended for functional testing. Bob provided
him with a custom build that integrated the mock payment gateway to avoid using the production gateway.
Alex set up the application server with the custom build and the database server with obfuscated
production data. He took a backup of the application build and the database dump to utilize it to refresh the
testing environment every time a fresh round of performance testing was needed.
■■Tip Use mock services of third-party applications while doing performance testing.
Using JMeter
Before starting with the test script development, Alex went through the JMeter component definitions.
• Test Plan: Every JMeter test script contains a test plan as a root node. It contains a
thread group, which contains one or more of the following child nodes:
Sampler, Logical Controller, Listener, Assertions, Timer, Config Element
• Thread Group: This is synonymous to a web user.
• Samplers: Send requests to the server. JMeter ships with many samplers out of which
the HTTP Request Sampler is used most often. It is used to simulate a web request.
• Logical Controllers: Provide common programming constructs that provide control
flow and are used to structure JMeter test scripts. Using controllers, you can specify
the order in which the samplers are processed.
• Listeners: Used to display the results of the server responses generated due to
sampler requests. They are processed at the end of the scope in which they are
found.
• Assertions: Used to validate the server responses generated due to sampler requests.
For example, to verify that for a HTTP request, the HTTP Response Code is 200.
• Timers: Used to insert a delay before the sampler is executed. These are used to
simulate the user think time before the next action. They are processed before
each sampler in the scope in which they are found. Timers are only processed in
conjunction with a sampler.
• Config Elements: Used to set up defaults and variables for later use by other
components. They are processed at the start of the scope in which they are found.
249
Chapter 11 ■ Case Study: Digital Toys Inc.
Alex started with the development of JMeter test scripts based on the use-cases. He followed an
incremental approach and learned along the way.
6.
Save the test plan as DTHomePageTestPlan.jmx.5
5
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTHomePageTestPlan.jmx
250
Chapter 11 ■ Case Study: Digital Toys Inc.
251
Chapter 11 ■ Case Study: Digital Toys Inc.
In these results, the recorded steps have requests for .bmp, .css, .js, .git, .ico, .jpeg, .png,
.swf, .woff, .woff2, and .ttf files, which are not required. Alex wanted to exclude these requests. He
decided to delete the previous recording and re-record the test. You would follow these steps to do so:
1.
In JMeter, click on the Stop button.
2.
To delete the recording, select all the recorded browser requests and go to Edit ➤
Remove. Confirm the dialog box.
252
Chapter 11 ■ Case Study: Digital Toys Inc.
3.
Exclude these regular expressions (see Figure 11-3):
.*\.(bmp|css|js|gif|ico|jpe?g|png|swf|woff|woff2|ttf).*
4.
Click on the Start button.
5.
In the Firefox browser, perform the steps of the use-case called User
Registration.
6.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
7.
Select all recorded browser actions from WorkBench, and then drag and add
them as child elements of Thread Group.
8.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
9.
Save the test plan as DTUserRegistrationTestPlan.jmx.6
Alex now understood the process of creating a test script by recording browser activity. He now had a
test script that performed user registration. Next, Alex wanted to simulate the load of hundreds of users.
Alex learned about a configuration element called CSV Data Set Config, which is used to load data from
a file in .csv format. He planned to use it to load the user details for the user registration form.
Alex followed these additional steps.
1.
Click on the user registration HTTP request POST request and go to Edit ➤ Add ➤
Config Element. Add CSV Data Set Config.
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTUserRegistrationTestPlan.jmx
6
253
Chapter 11 ■ Case Study: Digital Toys Inc.
2.
Configure CSV Data Set Config, as shown in Figure 11-4.
3.
Save the test plan.
Create the user.csv file containing the user details organized into three columns: fullName, email, and
password. Place the file in the same directory as the test script.
Jagdeep,[email protected],1234
Sai,[email protected],1234
Ganesh,[email protected],1234
Gopal,[email protected],1234
Alex now learned the process of parameterization in JMeter by passing the values from an external CSV
file. He followed the additional steps to configure the test plan to register the users listed in the user.csv file.
1.
Click on Thread Group and configure the Number of Threads (Users) as equal
to the number of rows in the user.csv file.
2.
Save the test plan.
3.
Run the test.
After the test run, Alex noted that the users in the user.csv file were generated successfully. By using
the username/password to manually log in to the Digital Toys Inc. web application, he verified that the order
was created.
254
Chapter 11 ■ Case Study: Digital Toys Inc.
7
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTFirstOrderTestPlan.jmx
255
Chapter 11 ■ Case Study: Digital Toys Inc.
■■Tip Use HTTP Request Defaults and keep the server configuration in one place to make the test plan
portable. If the test environment changes, it is an easy matter to change it, as it needs to be updated just in one
place.
8
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTSecondTimeOrderTestPlan.jmx
256
Chapter 11 ■ Case Study: Digital Toys Inc.
9
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangeAddressTestPlan.jmx
257
Chapter 11 ■ Case Study: Digital Toys Inc.
6.
Click on the Start button.
7.
In the Firefox browser, perform the steps of the use-case called User Editing
Payment Information.
8.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
9.
Select all recorded browser actions from WorkBench, and then drag and add
them as child elements of Thread Group.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
11.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP Request
Defaults. Configure Server Name or IP as localhost and Port Number as 8080.
12.
Remove the values of Server Name or IP and Port Number from each HTTP
request.
13.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
14.
Save the test as DTChangePaymentInfoTestPlan.jmx.10
15.
Run the test.
Alex was able to verify that the old payment information was updated.
Use-Case # 7 User Uses the Continue Shopping Option.
Alex configured the browser and JMeter to listen on the same port and followed these steps to record
another use-case.
1.
Create a test plan and give it a meaningful name, such as User Using Continue
Shopping Option.
2.
Click on WorkBench and go to Edit ➤ Add ➤ Non-Test Elements. Add HTTP(S)
Script Test Recorder.
3.
In the Global Settings, configure Port as 7070.
4.
Select Target Controller as WorkBench > HTTP(S) Test Script Recorder.
5.
Exclude the regular expression as:
.*\.(bmp|css|js|gif|ico|jpe?g|png|swf|woff|woff2|ttf).*
6.
Click on the Start button.
7.
In the Firefox browser, perform the steps of the use-case called User Using
Continue Shopping Option.
8.
Click on Test Plan and go to Edit ➤ Add ➤ Threads (Users). Add Thread Group.
9.
Select all recorded browser actions from WorkBench, and then drag and add
them as child elements of Thread Group.
10.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP
Cookie Manager.
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangePaymentInfoTestPlan.jmx
10
258
Chapter 11 ■ Case Study: Digital Toys Inc.
11.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add HTTP Request
Defaults. Configure Server Name or IP as localhost and Port Number as 8080.
12.
Remove the values of Server Name or IP and Port Number from each HTTP
request.
13.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add View Results Tree.
14.
Save the test as DTContinueShoppingTestPlan.jmx.11
15.
Run the test.
Alex was able to verify that the new order with multiple products was created, and it was visible in the
web application under order history.
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTContinueShoppingTestPlan.jmx
11
12
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTHomePageTestPlan.jmx
259
Chapter 11 ■ Case Study: Digital Toys Inc.
Alex change 500 back to 200 and saved the updated test plan. The test was then successful.
■■Caution Login and subsequent logout are required to make sure that the session is closed. Otherwise, it
may impact the overall performance results.
Alex followed these steps and updated the existing test plan.
1.
Open DTFirstOrderTestPlan.jmx.14
2.
Click on /user/signIn HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
3.
Click on /order/addToCart HTTP Request and go to Edit ➤ Add ➤ Assertions.
Add Response Assertion. Configure Apply to as Main Sample Only, Response
Field To Test as Response Code, Pattern Matching Rules as Equals, and
Patterns To Test as 200.
4.
Click on /user/addAddress HTTP Request and go to Edit ➤ Add ➤ Assertions.
Add Response Assertion. Configure Apply to as Main Sample Only, Response
Field To Test as Response Code, Pattern Matching Rules as Equals, and
Patterns To Test as 200.
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTUserRegistrationTestPlan.jmx
13
14
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTFirstOrderTestPlan.jmx
260
Chapter 11 ■ Case Study: Digital Toys Inc.
5.
Click on /user/addCard HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
6.
Click on /user/signOut HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
7.
Save the updated test plan.
8.
Run the test.
The results indicated that the test passed successfully.
Use-Case # 4 User Places an Order for the Second Time.
The next test plan also had multiple HTTP request-response sequences. Alex decided to focus
on /user/signIn, /order/addToCart, and /user/signOut POST requests and added assertions.
Alex followed these steps to update the existing test plan.
1.
Open DTSecondTimeOrderTestPlan.jmx.15
2.
Click on /user/signIn HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
3.
Click on /order/addToCart HTTP Request and go to Edit ➤ Add ➤ Assertions.
Add Response Assertion. Configure Apply to as Main Sample Only, Response
Field To Test as Response Code, Pattern Matching Rules as Equals, and Patterns
To Test as 200.
4.
Click on /user/signOut HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
5.
Save the updated test plan.
6.
Run the test.
The results indicated that the test passed successfully.
Use-Case # 5 User Edits the Billing/Shipping Address.
This test plan also had multiple HTTP request-response sequences. Alex decided to focus on /user/
signIn, /order/addAddress, and /user/signOut POST requests and added assertions.
Alex followed these steps to update the existing test plan.
1.
Open DTChangeAddressTestPlan.jmx.16
2.
Click on /user/signIn HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
15
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTSecondTimeOrderTestPlan.jmx
16
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangeAddressTestPlan.jmx
261
Chapter 11 ■ Case Study: Digital Toys Inc.
3.
Click on /order/addAddress HTTP Request and go to Edit ➤ Add ➤ Assertions.
Add Response Assertion. Configure Apply to as Main Sample Only, Response
Field To Test as Response Code, Pattern Matching Rules as Equals, and
Patterns To Test as 200.
4.
Click on /user/signOut HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
5.
Save the updated test plan.
6.
Run the test.
The results indicated that the test passed successfully.
Use-Case # 6 User Edits Payment Information.
This test plan also has multiple HTTP request-response sequences. Alex decided to focus on
/user/signIn, /order/addCard, and /user/signOut POST requests and added assertions.
Alex followed these steps to update the existing test plan.
1.
Open DTChangePaymentInfoTestPlan.jmx.17
2.
Click on /user/signIn HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
3.
Click on /order/addAddress HTTP Request and go to Edit ➤ Add ➤ Assertions.
Add Response Assertion. Configure Apply to as Main Sample Only, Response
Field To Test as Response Code, Pattern Matching Rules as Equals, and
Patterns To Test as 200.
4.
Click on /user/signOut HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
5.
Save the updated test plan.
6.
Run the test.
The results indicated that the test passed successfully.
Use-Case # 7 User Uses the Continue Shopping Option.
This test plan also had multiple HTTP request-response sequences. Alex decided to focus on /user/
signIn, /order/addToCart, /user/addAddress, /order/addCard, and /user/signOut POST requests and
added assertions.
Alex followed these steps to update the existing test plan.
1.
Open DTContinueShoppingTestPlan.jmx.18
2.
Click on /user/signIn HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangePaymentInfoTestPlan.jmx
17
18
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTContinueShoppingTestPlan.jmx
262
Chapter 11 ■ Case Study: Digital Toys Inc.
3.
Click on /order/addToCart HTTP Request and go to Edit ➤ Add ➤ Assertions.
Add Response Assertion. Configure Apply to as Main Sample Only, Response
Field To Test as Response Code, Pattern Matching Rules as Equals, and
Patterns To Test as 200.
4.
Click on /user/addAddress HTTP Request and go to Edit ➤ Add ➤ Assertions.
Add Response Assertion. Configure Apply to as Main Sample Only, Response
Field To Test as Response Code, Pattern Matching Rules as Equals, and
Patterns To Test as 200.
5.
Click on /user/addCard HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
6.
Click on /user/signOut HTTP Request and go to Edit ➤ Add ➤ Assertions. Add
Response Assertion. Configure Apply to as Main Sample Only, Response Field
To Test as Response Code, Pattern Matching Rules as Equals, and Patterns To
Test as 200.
7.
Save the updated test plan.
8.
Run the test.
The results indicated that the test passed successfully.
19
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangeAddressTestPlan.jmx
263
Chapter 11 ■ Case Study: Digital Toys Inc.
3.
Pass the reference name to the next HTTP request, as shown in Figure 11-7.
4.
Save the updated test plan.
Updating Change Payment Information Test Plan.
1.
Open DTChangePaymentInfoTestPlan.jmx.20
2.
Click on /user/addCard HTTP Request and go to Edit ➤ Add ➤ Post
Processors. Add Regular Expression Extractor. Configure Reference Name as
cardid, Regular Expression as <input type="hidden" name="addressId"
value="(.+?)" id="addressId" \/> that he found from the HTML code,
Template as $1$, and Match No. (0 for Random) as 1 (see Figure 11-8).
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangePaymentInfoTestPlan.jmx
20
264
Chapter 11 ■ Case Study: Digital Toys Inc.
3.
Pass the reference name to the next HTTP request, as shown in Figure 11-9.
4.
Save the updated test plan.
265
Chapter 11 ■ Case Study: Digital Toys Inc.
3.
Click on the same /user/signIn HTTP request and configure parameters in the
request transaction (see Figure 11-11).
4.
Save the updated test plan.
21
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTFirstOrderTestPlan.jmx
266
Chapter 11 ■ Case Study: Digital Toys Inc.
Alex updated the remaining test plans by opening each plan one by one and following the previous
steps.
• DTSecondTimeOrderTestPlan.jmx
• DTChangeAddressTestPlan.jmx
• DTChangePaymentInfoTestPlan.jmx
• DTContinueShoppingTestPlan.jmx
To simulate the load of 10 concurrent users, Alex ensured that the dt-users.csv file mentioned in the
CSV Data Set Config had 10 users.
The next step was to configure Thread Group with the number of concurrent users and run the test.
Use-Case # 1 User Lands on the Home Page and Browses the Products.
1.
Open DTHomePageTestPlan.jmx.22
2.
Click on Thread Group. In Thread properties, configure Number of Threads
(users) as 10, Ramp-Up Period (in seconds) as 1, and Loop Count as 1.
3.
Save the updated test plan.
4.
Run the test.
The results are shown in Figure 11-12.
22
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTHomePageTestPlan.jmx
267
Chapter 11 ■ Case Study: Digital Toys Inc.
23
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTFirstOrderTestPlan.jmx
24
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTSecondTimeOrderTestPlan.jmx
268
Chapter 11 ■ Case Study: Digital Toys Inc.
25
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangeAddressTestPlan.jmx
269
Chapter 11 ■ Case Study: Digital Toys Inc.
26
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangePaymentInfoTestPlan.jmx
270
Chapter 11 ■ Case Study: Digital Toys Inc.
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTContinueShoppingTestPlan.jmx
27
271
Chapter 11 ■ Case Study: Digital Toys Inc.
Noting that the number of products purchased depends on the user, Alex wanted to allow for this and
followed these steps to achieve the actual user behavior.
1.
Click on Thread Group and go to Edit ➤ Add ➤ Config Element. Add Random
Variable. Configure Variable Name as numberOfProduct, Minimum Value as 1,
Maximum Value as 6, and under Per Thread (User)? as True (see Figure 11-18).
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTContinueShoppingTestPlan.jmx
28
272
Chapter 11 ■ Case Study: Digital Toys Inc.
2.
Click on Loop Controller. Configure Loop Count as the random variable
${numberOfProduct} (see Figure 11-19).
3.
Click on Loop Controller and go to Edit ➤ Add ➤ Config Element. Add Counter.
Configure as shown in Figure 11-20.
Figure 21-20. Counter
4.
Click on /product/detail HTTP Request. In the Send Parameters With
Request field, click on the Add button to add a name-value pair. Configure the
Name as productId and the Value as ${productId}.
5.
Click on /order/addToCart HTTP Request. In the Send Parameters With
Request field, click on the Add button to add a name-value pair. Configure the
Name as productId and the Value as ${productId} (see Figure 11-21).
273
Chapter 11 ■ Case Study: Digital Toys Inc.
6.
Save the updated test plan.
Users typically spend time on the product catalog page thinking about their next action. This can be
simulated by using a timer. Alex decided to use a Gaussian random timer and estimated that the user would
take 2 to 10 seconds. He followed these steps.
1.
Click on /product/detail GET HTTP Request and go to Edit ➤ Add ➤ Timer.
Add Gaussian Random Timer. Configure Deviation (in milliseconds) as 2000
and Constant Delay Offset (in milliseconds) as 10000.
2.
Click on /user/addAddress POST HTTP Request and go to Edit ➤ Add ➤ Timer.
Add Gaussian Random Timer. Configure Deviation (in milliseconds) as 2000
and Constant Delay Offset (in milliseconds) as 10000.
3.
Click on /user/addCard POST HTTP Request and go to Edit ➤ Add ➤ Timer.
Add Gaussian Random Timer. Configure Deviation (in milliseconds) as 2000
and Constant Delay Offset (in milliseconds) as 10000.
4.
Click on /order/orderHistory GET HTTP Request and go to Edit ➤ Add ➤ Timer
and add Gaussian Random Timer. Configure Deviation (in milliseconds) as 2000
and Constant Delay Offset (in milliseconds) as 10000 (see Figure 11-22).
274
Chapter 11 ■ Case Study: Digital Toys Inc.
Alex added a Gaussian random timer on all the pages that required user thinktime in all the test plans.
After updating the JMeter test script, Alex was confident that the script would implement the actual user
behavior. For each of the tests, he prepared a list of users and updated the CSV Data Set Config configuration
as per Table 11-11.
It makes sense to run the test for Placing the Order the Second Time, Editing the Address Information,
and Editing the Payment Information only after running the test for Placing the Order the First Time.
■■Tip Ensure that the sequence in which the tests are run follows the real user scenario.
Results Metrics
Once the tests are agreed upon, they are standardized and the results noted as a baseline. The test
results, together with the required performance metrics, are shared with the engineering team. When the
engineering team implements a fix, the tests are re-run and the results are compared with the baseline.
Alex had a discussion with the team and standardized on the performance criteria to be measured.
These were the Average, Min, and Max response times of each HTTP request. They also needed the
utilization metrics for CPU, memory, and network.
Alex added an aggregate report, which gave him Average, Min, and Max response times of each HTTP
request. He added jp@gc - PerfMon Metrics Collector to get CPU, memory, and network utilization stats.
275
Chapter 11 ■ Case Study: Digital Toys Inc.
Alex disabled the View Results Tree report for the production run, as it is memory intensive.
As JMeter does not ship with PerMon Agent out of the box, Alex downloaded the server agent from
Server Agent URL.29
In order to add jp@gc - PerfMon Metrics Collector to JMeter, Alex downloaded the plugin from
JMeterPlugins URL30 and extracted it to the JMeter main directory.
Alex followed these steps to update the existing test plans.
Use-Case # 1 User Lands on the Home Page and Browses Products.
1.
Open DTHomePageTestPlan.jmx.31
2.
Click on View Results Tree and go to Edit ➤ Disable.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add Aggregate Report.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add jp@gc - PerfMon
Metrics Collector.
5.
Click the Add Row button on the respective servers to monitor for CPU, memory,
and network.
6.
Run the test.
The results are shown in Figure 11-23.
The PerfMon Metrics Collectors report does not show many of the changes if you just trigger with
10 threads. Try to increase the threads to 100 and then run the test; you will find the results shown in
Figure 11-24.
29
http://jmeter-plugins.org/downloads/file/ServerAgent-2.2.1.zip
30
http://jmeter-plugins.org/downloads/file/JMeterPlugins-Standard-1.3.1.zip
31
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTHomePageTestPlan.jmx
276
Chapter 11 ■ Case Study: Digital Toys Inc.
Figure 11-24. Home page PerfMon report (see color image in source code file)
In the same way, he updated the remaining test plans and generated the reports.
Use-Case # 3 User Places an Order for the First Time.
1.
Open DTFirstOrderTestPlan.jmx.32
2.
Click on View Results Tree and go to Edit ➤ Disable.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add jp@gc - PerfMon
Metrics Collector.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add Aggregate Report.
5.
Click on the Add Row button on the respective servers to monitor for CPU,
memory, and network.
6.
Save the updated test plan.
7.
Run the test.
32
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTFirstOrderTestPlan.jmx
277
Chapter 11 ■ Case Study: Digital Toys Inc.
Figure 11-26. First order PerfMon report (see color image in source code file)
278
Chapter 11 ■ Case Study: Digital Toys Inc.
33
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTSecondTimeOrderTestPlan.jmx
279
Chapter 11 ■ Case Study: Digital Toys Inc.
Figure 11-28. Second time order PerfMon report (see color image in source code file)
34
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangeAddressTestPlan.jmx
280
Chapter 11 ■ Case Study: Digital Toys Inc.
Figure 11-30. Change address PerfMon report (see color image in source code file)
281
Chapter 11 ■ Case Study: Digital Toys Inc.
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangePaymentInfoTestPlan.jmx
35
282
Chapter 11 ■ Case Study: Digital Toys Inc.
Figure 11-32. Change payment info PerfMon report (see color image in source code file)
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTContinueShoppingTestPlan.jmx
36
283
Chapter 11 ■ Case Study: Digital Toys Inc.
3.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add Aggregate Report.
4.
Click on Thread Group and go to Edit ➤ Add ➤ Listener. Add jp@gc - PerfMon
Metrics Collector.
5.
Click on the Add Row button on jp@gc - PerfMon Metrics Collector and add the
respective servers to monitor for CPU, memory, and network.
6.
Save the updated test plan.
7.
Run the test.
Results are shown in Figures 11-33 and 11-34.
284
Chapter 11 ■ Case Study: Digital Toys Inc.
Figure 11-34. Continue shopping PerfMon report (see color image in source code file)
Organizing Tests
Alex captured the results from the aggregate report and the jp@gc - PerfMon Metrics Collector report and
showed them to his manager. Bob wanted Alex to identify the problematic use-cases, web pages, and their
associated HTTP requests for further analysis by the team.
285
Chapter 11 ■ Case Study: Digital Toys Inc.
Each use-case is a sequence of steps and each step comprises multiple HTTP requests. Alex prepared a
table showing the steps and the HTTP requests associated with each step.
Alex combined HTTP requests associated with a use-case under a transaction controller and named
them with the step name. This allows the report to display results on a per-step basis. Alex followed the table
and modified the other test scripts in a similar way.
Use-Case # 1 User Lands on the Home Page and Browses the Products.
Table 11-12. Use-Case # 1 Test Plan Steps Vs. HTTP Request Mapping
1.
Open DTHomePageTestPlan.jmx.37
2.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add Transaction
Controller. Configure Generate Parent Sample as true and Name as Home Page.
3.
Save the updated test plan.
4.
Run the test.
Results are shown in Figure 11-35.
37
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTHomePageTestPlan.jmx
286
Chapter 11 ■ Case Study: Digital Toys Inc.
Table 11-13. Use-Case # 2 Test Plan Steps Vs. HTTP Request Mapping
38
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTFirstOrderTestPlan.jmx
287
Chapter 11 ■ Case Study: Digital Toys Inc.
Table 11-14. Use-Case # 4 Test Plan Steps Vs. HTTP Request Mapping
288
Chapter 11 ■ Case Study: Digital Toys Inc.
1.
Open DTSecondTimeOrderTestPlan.jmx.39
2.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add
Transaction Controller. Configure Generate Parent Sample to make it true.
3.
Click on Transaction Controller and go to Edit ➤ Copy. Follow this step 8 times.
4.
Follow Table 11-14 and update the name of each transaction controller and the
associated request.
5.
Before running the test, Alex ran the First Order test with the same set of users
assigned for this test script.
6.
Save the updated test plan.
7.
Run the test.
The results are shown in Figure 11-37.
39
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTSecondTimeOrderTestPlan.jmx
289
Chapter 11 ■ Case Study: Digital Toys Inc.
Table 11-15. Use-Case # 5 Test Plan Steps vs. HTTP Request Mapping
1.
Open DTChangeAddressTestPlan.jmx.40
2.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add
Transaction Controller. Configure Generate Parent Sample to make it true.
3.
Click on Transaction Controller and go to Edit ➤ Copy. Follow this step four times.
4.
Follow Table 11-15 and update the name of each transaction controller and the
associated request.
5.
Before running the test, Alex ran the First Order test with the same set of users
assigned for this test script.
6.
Save the updated test plan.
7.
Run the test.
The results are shown in Figure 11-38.
40
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangeAddressTestPlan.jmx
290
Chapter 11 ■ Case Study: Digital Toys Inc.
Table 11-16. Use-Case # 6 Test Plan Steps Vs. HTTP Request Mapping
1.
Open DTChangePaymentInfoTestPlan.jmx.41
2.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add
Transaction Controller. Configure Generate Parent Sample to make it true.
3.
Click on Transaction Controller and go to Edit ➤ Copy. Follow this step four times.
4.
Follow Table 11-16 and update the name of each transaction controller and the
associated request.
5.
Before running the test, Alex ran the First Order test with the same set of users
assigned for this test script.
6.
Save the updated test plan.
7.
Run the test.
The results are shown in Figure 11-39.
41
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTChangePaymentInfoTestPlan.jmx
291
Chapter 11 ■ Case Study: Digital Toys Inc.
Table 11-17. Use-Case # 7 Test Plan Steps Vs. HTTP Request Mapping
1.
Open DTContinueShoppingTestPlan.jmx.42
2.
Click on Thread Group and go to Edit ➤ Add ➤ Logic Controller. Add
Transaction Controller. Configure Generate Parent Sample to make it true.
3.
Click on Transaction Controller and go to Edit ➤ Copy. Follow this step 11 times.
4.
Follow Table 11-17 and update the name of each transaction controller and the
associated request.
5.
Before running the test, Alex ensured that he ran the use-case User Placing the
First Order test with the same set of users as used in this test script.
6.
Save the updated test plan.
7.
Run the test.
42
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTContinueShoppingTestPlan.jmx
292
Chapter 11 ■ Case Study: Digital Toys Inc.
Before running the updated JMeter test scripts, Alex initialized his test environment by deploying a
clean schema. He wanted to be doubly sure that the test environment and the data were the same between
the test runs.
Alex ran the tests with 20 users to warm up the test environment. After that, he ran all the scripts with
500 users and approached Bob. Bob was happy to see results but asked for another set of tests where the
users were doing different operations at the same time.
■■Tip Run the test scripts with a few users as a warmup before running the real performance test.
2.
Click on Test Plan and go to Edit ➤ Merge. Select a test plan, as shown in Table 11-18.
3.
Save the test plan as DTMainTestPlan.jmx.43
43
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTMainTestPlan.jmx
293
Chapter 11 ■ Case Study: Digital Toys Inc.
He added each test plan listed in Table 11-18 as a thread group under Digital Toys Main.
After making the required changes, the test plan looked as shown in Figure 11-41.
Before running the updated JMeter test scripts, Alex initialized his test environment by deploying clean
schema.
The use-cases for DTSecondTimeOrderTestPlan.jmx, DTChangeAddressTestPlan.jmx, and
DTChangePaymentInfoTestPlan.jmx require that an initial order be placed in the system. For this, Alex
runs the DTFirstOrderTestPlan.jmx test with an input user file. This also serves to warm up the test
environment.
294
Chapter 11 ■ Case Study: Digital Toys Inc.
In order to run the test in parallel mode, Alex ensured that the Run Thread Groups Consecutively
(i.e. run groups one at a time) option was unchecked (which is the default) (see Figure 11-42).
295
Chapter 11 ■ Case Study: Digital Toys Inc.
He added an aggregate report and jp@gc - PerfMon Metrics Collector to generate the reports.
1.
Click on Test Plan and go to Add ➤ Listener. Add Aggregate Report.
2.
Click on Test Plan and go to Add ➤ Listener. Add jp@gc - PerfMon Metrics
Collector.
3.
Disable Aggregate Report and jp@gc - PerfMon Metrics Collector for the
individual thread group to save on CPU/memory consumption.
4.
Save the updated test plan.
5.
Run the test.
The results are shown in Figures 11-43 and 11-44.
296
Chapter 11 ■ Case Study: Digital Toys Inc.
Figure 11-44. Digital Toys main test (see color image in source code file)
Questions
Bob and the team asked Alex a few questions:
Question: How do you obtain a count of logged-in users at any point in time?
Answer: Alex replied that this could be obtained from the jp@gc - Active Threads Over Time report.
Question: What is the count of users doing various activities (browsing the catalog, ordering, changing
address, entering payment information, etc.) on the web site?
Answer: Alex said that this could be obtained by using the User Load Pattern table.
To simulate a load of 100,000 users, the number of threads (users) for each use-case can be calculated using
the % distribution detailed in the table.
Question: How do you simulate varying user-load patterns based on the time of the day and duration?
Answer: Alex replied that he would configure the Scheduler field of Thread Group.
Question: How do you run the performance test for multiple days?
Answer: Alex replied that he could configure the thread group scheduler, loop controller, and timer to
continuously run the test for a few days.
297
Chapter 11 ■ Case Study: Digital Toys Inc.
■■Note For a set of standard graphs and performance metrics, refer to Chapter 12, “Performance Dashboard”.
44
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_11/DTContinueShoppingTestPlan.jmx
298
Chapter 11 ■ Case Study: Digital Toys Inc.
Before starting the test, Alex configured the listeners to write to a file so that after the test, he could load
it into JMeter GUI and review performance results (see Figure 11-47).
Alex also set up the PerfMon Server Agent on the application server and configured it in the JMeter
test script so that he could monitor CPU, memory, and network, while executing tests from the slaves
(see Figure 11-48).
Alex ran the test from the console and showed the output here:
C:\>jmeter -n -t DTContinueShoppingTestPlan.jmx -r
Writing log file to: C:\github\jmeter-test-scripts\case-study\jmeter.log
Creating summariser <summary>
Created the tree successfully using DTContinueShoppingTestPlan.jmx
Configuring remote engine: 192.168.1.7
Configuring remote engine: 192.168.1.8
Starting remote engines
Starting the test @ Thu May 18 10:47:34 PDT 2017 (1495129654354)
Remote engines have been started
Waiting for possible Shutdown/StopTestNow/Heapdump message on port 4445
summary = 216 in 00:01:46 = 2.0/s Avg: 86 Min: 0 Max: 930 Err: 0 (0.00%)
Tidying up remote @ Thu May 18 10:49:23 PDT 2017 (1495129763436)
... end of run
C:\github\jmeter-test-scripts\case-study>
299
Chapter 11 ■ Case Study: Digital Toys Inc.
C:\apache-jmeter-3.0\bin>jmeter-server
Could not find ApacheJmeter_core.jar ...
... Trying JMETER_HOME=..
Found ApacheJMeter_core.jar
Writing log file to: C:\apache-jmeter-3.0\bin\jmeter-server.log
Created remote object: UnicastServerRef [liveRef: [endpoint:[192.168.1.7:53129]
(local),objID:[-34fbde0b:15c1c9dba9e:-7fff, 770769319327732
0207]]]
Starting the test on host 192.168.1.7 @ Thu May 18 10:47:09 PDT 2017 (1495129629730)
Finished the test on host 192.168.1.7 @ Thu May 18 10:48:56 PDT 2017 (1495129736089)
C:\>jmeter-server
Could not find ApacheJmeter_core.jar ...
... Trying JMETER_HOME=..
Found ApacheJMeter_core.jar
Writing log file to: C:\apache-jmeter-3.0\bin\jmeter-server.log
Created remote object: UnicastServerRef [liveRef: [endpoint:[192.168.1.8:49568](local),objID
:[19039a4:15c1c9de321:-7fff, 9104153584973333192]]]
Starting the test on host 192.168.1.8 @ Thu May 18 10:47:09 PDT 2017 (1495129629182)
Finished the test on host 192.168.1.8 @ Thu May 18 10:48:55 PDT 2017 (1495129735393)
The aggregate report captures the data of both the slaves. Alex has 10 threads configured in the test, and
with two slaves, that becomes 20 (see Figures 11-49 and 11-50).
300
Chapter 11 ■ Case Study: Digital Toys Inc.
Figure 11-50. PerfMon report distributed load (see color image in source code file)
■■Tip Use a distributed testing environment to generate more load on the application under test.
Outcome
After the new version of Digital Toys Inc. web application was deployed, Bob reviewed the analytics report
and was pleased to see a decrease in response time and an increase in user engagement.
301
Chapter 11 ■ Case Study: Digital Toys Inc.
After one month, in the senior management meeting, the Customer Support Manager reported a
decrease in support calls. Nancy, the CFO, reported an increase in revenue.
Martin, the CEO, was very pleased with the overall teamwork and the outcome of the performance testing
and tuning project. He thanked the team and recognized the importance of performance testing and tuning.
He allocated a budget and made performance testing and tuning mandatory for every production release.
Conclusion
In this chapter, you learned how Digital Toys Inc. solved its business problem by using JMeter for
performance test automation. You also learned how Alex planned from start to end and involved all the
stakeholders along the way. In the next chapter, you learn about the APDEX index and its use in analyzing
performance test results. You will also generate Performance Dashboards, which will be useful in
understanding load patterns. You will also learn about JVisualVM, which comes with Java by default.
302
CHAPTER 12
Performance Dashboard
This chapter discusses how to customize and generate the Performance Dashboard.
At the end of this chapter, you will have a good idea of the Performance Dashboard, including how it
should be generated and how to interpret it.
JMeter 3.0 introduced the concept of the Performance Dashboard, using which you can monitor and analyze
the performance of the web application under the test. It consists of a standard set of performance metrics
and graphs. These can be customized to suit specific needs.
APDEX
APDEX stands for Application Performance Index.1 It calculates a user satisfaction score, taking into account
user satisfaction levels.
The users are satisfied if the response times are below a certain threshold. The users who are tolerating
are unhappy with the web site performance but continue to use it grudgingly. The users who are frustrated
have exhausted their patience and abandon the web site Figure 12-1 shows the formula and Table 12-1
shows the APDEX levels.
Configuration
JMeter 3.0 has provided several properties to configure the Performance Dashboard. These properties are
present in the reportgenerator.properties file and they have to be copied to the user.properties file.
These properties have to be updated as per the requirements for generating graphs.
1
https://en.wikipedia.org/wiki/Apdex
The following sections provide the details to generate and customize the Performance Dashboard.
JMeter Properties
The following properties need to be set to true to allow the generation of graphs under the
jmeter.properties files.
jmeter.save.saveservice.label=true
jmeter.save.saveservice.response_code=true
jmeter.save.saveservice.response_message=true
jmeter.save.saveservice.successful=true
jmeter.save.saveservice.thread_name=true
jmeter.save.saveservice.thread_counts=true
jmeter.save.saveservice.latency=true
jmeter.save.saveservice.bytes=true
.
.
.
# Timestamp format - this only affects CSV output files
# legitimate values: none, ms, or a format suitable for SimpleDateFormat
jmeter.save.saveservice.timestamp_format=ms
jmeter.save.saveservice.timestamp_format=yyyy/MM/dd HH:mm:ss.SSS
We can generate the dashboard in a single step via the command line. Alternatively, the test is run and
the output is captured to a .csv file, which is then used to generate the Performance Dashboard.
APDEX
The following properties under the reportgenerator.properties file are used to configure the satisfaction
and tolerance thresholds.
# Sets the satisfaction threshold for the APDEX calculation (in milliseconds).
jmeter.reportgenerator.apdex_satisfied_threshold=500
# Sets the tolerance threshold for the APDEX calculation (in milliseconds).
jmeter.reportgenerator.apdex_tolerated_threshold=1500
# Regular Expression which Indicates which samples to keep for graphs and statistics
generation.
# Empty value means no filtering
#jmeter.reportgenerator.sample_filter=
304
Chapter 12 ■ Performance Dashboard
You can customize the title of the Performance Dashboard by configuring the report_title property.
You can also configure granularity of generated graphs by updating the overall_granularity property.
The samplers that will appear in the graphs can be filtered by updating the sample_filter property
with a suitable regular expression.
We can use the -o option to specify the output directory for the reports. This can be overridden by
configuring the output_dir property in the user.properties file.
jmeter.reportgenerator.graph.responseTimeVsRequest.exclude_controllers=true
jmeter.reportgenerator.graph.responseTimeVsRequest.property.set_granularity=${jmeter.
reportgenerator.overall_granularity}
It is a best practice to have the names of the transactions appear in the graph. To achieve, that do the
following:
1.
Name the Transaction Controller appropriately.
2.
Enable the Generate Parent Sample checkbox (see Figure 12-2).
305
Chapter 12 ■ Performance Dashboard
3.
Configure the following property as false:
jmeter.reportgenerator.graph.responseTimeVsRequest .exclude_controllers=false
The data points are aggregated based on the granularity, which can be configured using the following:
jmeter.reportgenerator.graph.responseTimeVsRequest.property.set_granularity=${jmeter.
reportgenerator.overall_granularity}
Generating Graphs
To generate the dashboard in a single step, execute the following command in the CMD prompt.
For example:
jmeter -n -t DTFirstOrderTestPlan.jmx -l dt-firstordertest-plan.jtl -e -o C:\tmp\
performance-dashboard\
306
Chapter 12 ■ Performance Dashboard
2
https://github.com/Apress/pro-apache-jmeter/blob/master/Matam_Ch_12/
DTPerformanceDashBoardTestPlan.jmx
307
Chapter 12 ■ Performance Dashboard
The Response Time Over Time graph illustrates how the response time changes over time. It draws our
attention to times when the response time was out of acceptable limits. Any such discrepancies should be
investigated by the team. From Figure 12-4, it is noted that the response time spiked twice: once at 23:33:00
and once at 23:41:00 (see Figure 12-4).
Figure 12-4. Response time over time (see color image in source code file)
The reason for the spikes can be inferred from the JVisualVM graph. You can see that the CPU also
spiked at the same time. The spike at 23:33:00 was due to general reasons and the spike at 23:41:00 can be
attributed to a garbage collection (GC) activity at the same time (see Figure 12-5).
308
Chapter 12 ■ Performance Dashboard
The Bytes Throughput Over Time graph shows data transfer during the request and response. This
is especially useful when your web application is data intensive. For example, for a photo or a file sharing
application (see Figure 12-6).
309
Chapter 12 ■ Performance Dashboard
The Hits Per Second graph shows user activity on the web site. By looking at this graph, you can be
assured that the web application was subjected to the desired load (see Figure 12-7).
The Codes Per Second graph shows HTTP response codes returned from the server. This graph is useful
to confirm that there were no excessive errors while load testing the web application (see Figure 12-8).
The Transactions Per Second graph shows the number of transactions for each use-case. This is useful
to confirm that the web application is getting the proper load with the desired mix of transactions
(see Figure 12-9).
310
Chapter 12 ■ Performance Dashboard
Figure 12-9. Transactions per second (see color image in source code file)
The Response Time Percentiles graph shows the response time deviation (refer APDEX) (see Figure 12-10).
Figure 12-10. Response time percentiles (see color image in source code file)
The Active Threads Over Time graph shows that the number of active users (Threads) are as planned
(see Figure 12-11).
311
Chapter 12 ■ Performance Dashboard
The Time Vs Threads graph shows the number of users (Threads) engaged in a particular transaction
over time. In the graph, you can select transactions to compare (see Figure 12-12).
Figure 12-12. Time vs threads (see color image in source code file)
312
Chapter 12 ■ Performance Dashboard
The Response Time Distribution graph shows the response time distribution to identify outliers
(see Figure 12-13).
Conclusion
In this chapter, you learned to configure and generate the Performance Dashboard. You also learned to
interpret the results.
313
CHAPTER 13
■■Note Readers who are already familiar with JMeter setup can start directly with the first chapter.
MacOSX
The following section explains how to install Java and JMeter on MacOSX. If you are using Windows or
Linux, skip to the appropriate section.
Download JDK
Download the Java Development Kit (JDK) from Oracle’s web site.1
JMeter requires Java Runtime Environment (JRE) to run. But for some of the advanced uses, we
recommend installing a complete development environment. Pick the latest JDK version for MacOSX.
This is usually found on the web page by name (jdk-8u60-macosx-x64.dmg). Double-click it and follow the
instructions on the screen (see Figures 13-1 and 13-2).
1
http://java.oracle.com
Install JDK
Follow the instructions and complete the installation. To verify the installation of the Java runtime, run the
following command in the terminal window.
$ java -version
java version "1.8.0_60" Java(TM)
SE Runtime Environment (build 1.8.0_60-b27)
Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode)
$ vim ~/.bash_profile
Or
$ vim ~/.profile
export JAVA_HOME=$(/usr/libexec/java_home)
Log out from the current terminal window and open a new terminal window to pick up the new
changes. Or, you can run the following command in the current terminal window.
316
Chapter 13 ■ Appendix A: Setting Up JMeter
Issue the following command to verify that JAVA_HOME has been set under the environment variables.
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home
Issue the following command to verify that JDK has been installed properly and you have Performance
Dashboard environment variable. (This verifies the Java compiler.)
$ javac -version
javac 1.8.0_60
Download JMeter
Download JMeter from the Apache web site.2
Pick the latest version of JMeter; as of now, the latest JMeter available is apache-jmeter-3.0.tgz.
Set Up JMeter
Setting up JMeter just involves extracting the JMeter binaries into the user-defined location on the user
machine. Assuming the downloaded JMeter binaries are in your Downloads folder, run the following
command in the terminal window.
Issue the following command in your terminal window to verify that you have extracted the JMeter
binaries correctly.
$ cd /usr/local/apache-jmeter-3.0/
$ ls -1p
LICENSE
NOTICE
README
bin/
docs/
extras/
lib/
licenses/
printable_docs/
It is good practice to set up the JMETER_HOME environment variable and add the following lines to the PATH.
Open ~/.bash_profile or ~/.profile to your favorite editor.
$ vim ~/.bash_profile
Or
$ vim ~/.profile
2
https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-3.0.tgz
317
Chapter 13 ■ Appendix A: Setting Up JMeter
export JMETER_HOME="/usr/local/apache-jmeter-3.0"
export PATH="$PATH:$JMETER_HOME/bin"
Log out from the current terminal window and open a new terminal window to pick up the changes.
Or you can run the following command in the current terminal window.
Now that you have set up JMeter, you can start JMeter by running the startup script.
Run the following command in the terminal window (see Figure 13-3).
$ jmeter
Windows
The following section shows you how to install Java and JMeter on Windows 7. If you are using MacOSX or
Linux, skip to the appropriate section.
Download JDK
Download the Java Development Kit (JDK) from Oracle’s web site.3
3
http://java.oracle.com
318
Chapter 13 ■ Appendix A: Setting Up JMeter
JMeter requires just the Java Runtime Environment (JRE) to run. But for some of the advanced uses,
we recommend installing a complete development environment. Pick the latest JDK for Windows. This is
usually found on the web page by name. They are called jdk-8u60-windows-x64.exe for 64-bit and
jdk-8u60windows-i586.exe for 32-bit. Depending on your machine configuration, download the required JDK.
Install JDK
Double-click the executable to launch the installer and follow the instructions (see Figures 13-4, 13-5, and 13-6).
319
Chapter 13 ■ Appendix A: Setting Up JMeter
To verify the installation of Java runtime, run the following command on the Windows command prompt.
Issue the following command to verify that JDK has been installed properly and you have set the correct
environment variable. (This verifies the Java compiler.)
320
Chapter 13 ■ Appendix A: Setting Up JMeter
Download JMeter
Download JMeter from the Apache web site.4
Pick the latest version of JMeter; as of the writing of this book, the latest JMeter available is
apachejmeter-3.0.zip.
Set Up JMeter
Setting up JMeter involves extracting the JMeter binaries at a user-defined location. Navigate to your
Downloads folder where you have downloaded the binaries, right-click the file, choose Extract All, and then
follow the instructions on the screen.
Once the extraction is complete, navigate to the JMeter folder to see the contents. The results will
resemble Figure 13-7.
It is a good practice to set up the JMETER_HOME environment variable and add this into the PATH.
4
https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-3.0.zip
321
Chapter 13 ■ Appendix A: Setting Up JMeter
To start Jmeter, run the following command on your Windows command prompt.
C:\> cd C:\apache-jmeter-3.0\bin
C:\apache-jmeter-3.0\bin> jmeter.bat
Linux
The following section explains how to install Java and JMeter on Linux. If you are using MacOSX or
Windows, skip to the appropriate section.
Install JDK
On Fedora, Oracle Linux, and Red Hat Enterprise Linux, open the terminal window and issue the following
command.
Open JDK Java 8 was released in March 2014 and has been made into official Ubuntu repositories for
14.10 Utopic and higher. For Ubuntu 14.04, Ubuntu 12.04, and Linux Mint 17, you have to install it from PPA.
It’s available in Ubuntu Software Center for Ubuntu 14.10 and Ubuntu 15.04.
Open the terminal window in Ubuntu and issue the following command.
322
Chapter 13 ■ Appendix A: Setting Up JMeter
For more information on JDK installation, check the JDK installation web site.5
To verify the installation of Java runtime, run the following command in the terminal window.
$ java -version
openjdk version "1.8.0_45-internal"
OpenJDK Runtime Environment (build 1.8.0_45-internal-b14)
OpenJDK 64-Bit Server VM (build 25.45-b02, mixed mode)
$ gedit ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-adm64
PATH=$PATH:$JAVA_HOME/bin
Log out from the current terminal window and open a new terminal window to pick up the changes.
Or you can run the following command in the current terminal window.
$ source ~/.bashrc
Issue the following command to verify that JAVA_HOME has been set under the environment variables.
$ echo $JAVA_HOME
/usr/lib/jvm/java-8-openjdk-adm64
Issue the following command to verify that JDK has been installed properly and you have set the correct
environment variable. (This verifies the Java compiler.)
$ javac -version
javac 1.8.0_45-internal
Download JMeter
Download JMeter from the Apache web site.6
Pick the latest version of JMeter; as of the writing of this book, the latest JMeter available is
apachejmeter-3.0.tgz.
5
http://openjdk.java.net/install/
6
https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-3.0.tgz
323
Chapter 13 ■ Appendix A: Setting Up JMeter
Set Up JMeter
Setting up JMeter just involves extracting the JMeter binaries at a user-defined location. Assuming the
downloaded JMeter binaries are in your Downloads folder, run the following command in the terminal
window.
Issue the following command in your terminal window to verify that you have extracted JMeter
binaries correctly.
$ cd /usr/local/apache-jmeter-3.0/
$ ls -1p
bin/
docs/
extras/
lib/
LICENSE
licenses/
NOTICE
printable_docs/
README
It is good practice to set up the JMETER_HOME environment variable and add this into the PATH.
Open ~/.bashrc in your favorite editor and add the following lines.
$ gedit ~/.bashrc
export JMETER_HOME="/usr/local/apache-jmeter-3.0"
export PATH=$PATH:$JMETER_HOME/bin
Log out from the current terminal window and open a new terminal window to pick up the changes.
Or you can run the following command in the current terminal window.
$ source ~/.bashrc
Now that you have set up JMeter, you can start JMeter by running the JMeter startup script.
Run the following command in the terminal window (see Figure 13-9).
$ jmeter
324
Chapter 13 ■ Appendix A: Setting Up JMeter
■■Note Going forward, we use Windows-based examples, but you can use the same steps on MacOS or any
Linux OS.
325
CHAPTER 14
We have used the Digital Toys Inc. web application for explaining the examples in this book. We describe
setting up this web application in this chapter.
■■Note Make sure that you have JDK 8.0 installed on your machine. The Digital Toys Inc. web application
has been complied using JDK 8.0.
C:\>startDt.bat
1
https://github.com/Apress/pro-apache-jmeter/tree/master/digital-toys-web-application
328
Chapter 14 ■ Appendix B: Setting Up Digital Toys Inc.
If you want to start the Digital Toys Inc. web application on a different port, enter this command in the
CMD prompt:
Open the browser and launch http://localhost:8080/dt. A home page will be shown as the landing
page of the Digital Toys Inc. web application (see Figure 14-1).
329
Chapter 14 ■ Appendix B: Setting Up Digital Toys Inc.
C:\>set SESSION_IN_URL=true
C:\>startDt.bat
330
Chapter 14 ■ Appendix B: Setting Up Digital Toys Inc.
■■Tip Rev This is required for running the preprocessors test plan.
Clean Up
After jetty-runner has started, it will create two files.
Open the CMD prompt and execute the following command:
C:\>dir prodDb*
Volume in drive C has no label.
Volume Serial Number is DA32-01EE
Directory of C:\
C:\>
These files save data. They are useful for deleting files before starting with a fresh chapter.
331
Index
A, B, C
Foundation
why JMeter?, 2
Case study why performance testing?, 1
exclude regular expression, 253, 255–258
J, K, L, M, N, O
D, E
JMeter best practices
Distributed testing, 165, 167–177 CSV data set config, 192–194
batch mode, 173–174 HTTP cookie manager, 184
custom implementation mode, 175 HTTP request defaults, 179–180
DiskStore mode, 174 JMeter Plugins
GUI Mode, 171–172 JMeter Plugins at Google Code (JP@GC), 211
hold mode, 174 JMeter Properties, 218
limitations, 177 PerfMon, 211–219
master-slave, 167, 172, 173 ServerAgent, 212–214
server port, 172, 173 JMeter Recipes
statistical mode, 174 FTP-performance
StrippedAsynch mode, 175 file transfer protocol (FTP), 228–230
StrippedBatch mode, 175 JDBC performance testing
StrippedDiskStore mode, 174 JDBC test plan, 224–227
Stripped mode, 174–175 mobile performance testing
unreachable remote host, 176–177 characters per second (cps), 234
mobile device, 234, 235
F, G, H, I
User-Agent, 234
REST-JSON performance testing
First JMeter Test HttpClient4, 231
assertions, 14 REST, 230–232
configuration elements, 14 SOAP performance testing
controller, 14 SOAP, 237–242
executing a single test, 23 JMeter test plan components
GUI mode, 21–22 assertions
listener, 14 apply to, 129
post-processor, 15 assertion results listener, 128
pre-processor, 15 pattern matching rules, 128–130
proxy server setting, 24 pattern to test, 130–138
sampler, 14 response assertion, 128
start JMeter in server mode, 24 response field to test, 129
stop/shutdown JMeter, 24 Controller
test plan, 13 ForEach Controller, 85–87
thread groups, 13 If Controller, 87–92
timer, 14 Interleave Controller, 76–81
334
■ INDEX
T, U, V, W, X, Y, Z
java.RMI.Remote
Exception, 200
Troubleshooting JMeter JMeter logging level, 198
execute permissions, 197 log file, 197
HTTP Basic Authentication, 204 Log Viewer, 199, 200
HTTPClient, 199 proxy server, 202–203
335