Quick Start for JMeter Interface Testing

Time:2022-8-18

Introduction to JMeter

JMeterFeatures:

  • Functional testing and performance testing for multiple protocols

    • Web – HTTP, HTTPS (Java, NodeJS, PHP, ASP.NET, …)
    • SOAP / REST Webservices
    • FTP
    • Database via JDBC
    • LDAP
    • Message-oriented middleware (MOM) via JMS
    • Mail – SMTP(S), POP3(S) and IMAP(S)
    • Native commands or shell scripts
    • TCP
    • Java Objects
  • Test recording provided
  • supplyCLImodel
  • supplyHTMLReport
  • Complete portability and 100% pureJava
  • Provides multi-threading support to simulate multiple users
  • High scalability > This section is translated fromJMeterfront page:https://jmeter.apache.org/index.html

    Author's experimental environment

JMeter is an implementation of the Java language, that is, a pure Java application, so JMeter can theoretically run on any environment where the corresponding Java environment is available. |type|value| |:—-|:—-| |Java version|java version "1.8.0_181" (requires Java8 and above)| |JMeter version|5.4.1| |OS|Ubuntu 20.04 (GNOME 3.36. 5) | |Kernel Version|Linux version 5.8.0-43-generic|

download

This article mainly introducesJMeteris a quick start, so other environments are prepared by the readers themselves

  1. Enter the official website page (https://jmeter.apache.org/download_jmeter.cgi) select the appropriate mirror source and download the binary distribution file;
  2. After decompressing the compressed file to the local,JMeterThe path to the resulting directory after decompression is calledJMETER_HOME

A brief introduction to JMeter files

file path (relative to the JMETER_HOME directory) File Description
bin folder where executable files are stored
docs Help document directory
extras Expand the plugin directory, the files in the directory provide support for ant
lib The jar package used by JMeter
bin/jmeter Executable to start JMeter client in linux and unix systems (itself a shell script)
bin/jmeter-server Executable file (itself a shell script) that starts the JMeter service process in linux and unix systems
bin/jmeter.properties JMeter configuration file
bin/jmeter.bat Executable file to start JMeter client under Windows
bin/jmeter-server.bat Executable file to start JMeter service process under Windows

Start the JMeter UI

EnterJMETER_HOMEunder the directorybindirectory, execute the following command to startJMeterofGUImodel:

./jmeter


After a few seconds, the interface opens as follows:

Quick Start for JMeter Interface Testing

Introduction to the main concepts of JMeter

concept Introduction
Test Plan A test plan describes a series of steps that JMeter needs to perform
thread group A thread group defines the user pool for execution (simulates multiple users in a concurrent fashion)
jmx file A file ending in (.jmx) corresponding to a test plan, in which the JMeter program-specific data structure is organized in xml format
Sampler (sample) The sampler can sample the executed target (types such as HTTP, JDBC, etc.)
pre-processor Preprocess the sampler (provide user parameters, wait for a specified time, etc.)
post-processor Post-processing the sampler (result extractor, etc.)
assertions Make assertions on the results obtained by the sampler (response time assertions, response data assertions, response structure assertions, etc.)
Logic controller Logically control the execution steps of the test plan (If, While, etc.)
listener After the sampler is executed, the listener will be notified, and the general listener is used to process the result data (display the result data, aggregate the chart, etc.)
config element Ability to do some configuration for the test plan (request header configuration, common request configuration, authentication configuration, variable configuration, etc.)

Introduction to the main functional elements of JMeter (Http test related)

JMeterMost of the interface operations are to click the right mouse button and a drop-down menu will pop up to add elements.

thread group

Right click test plan to add

Component screenshot:

Quick Start for JMeter Interface Testing

Component parameter description:

parameter name Value and meaning
Action after error Continue (continue to the next step), start next loop, stop thread (this thread only), stop test (wait for executing sampler execution to finish), stop test immediately
Threads number of users to impersonate
Ramp-Up time (seconds) Warm-up time. Used to start all configured threads within the execution time. For example, 10s, the number of threads is 10, then a thread is started every 1s (the first thread is always started immediately, if the total number of threads is 1, no matter the value of the warm-up time, it is equivalent to 0)
Cycles Forever (the loop does not stop), specified number (after the specified number of loops, the execution stops)
Loop the same user each time? whether

HTTP request default

Right-click the thread group element and add it from the config element dropdown

This component is used for scopedHTTPThe sampler provides default values.Quick Start for JMeter Interface Testing

Component parameter description:

parameter name Value and meaning
protocol Is it http protocol or https protocol
Server name or IP Domain name or IP address
The port number port number of the server
path the path part in the URL
content encoding The character set encoding used by the HTTP request
parameter HTTP request parameters
message body data Default request body data

user-defined variable

Right-click the Thread Group element and select Add from the Configuration element

This component is used to define variables in the thread and can be used elsewhere${variableName}syntax for reference.

Click on the following interfaceAdd tobutton to add a line of variable name and value to define a variable.Quick Start for JMeter Interface Testing

HTTP Sampler

Right mouse click on thread group element, select from sampler entry

HTTP sampler can useHTTPThe system under test is sampled (initiated a request) in the form of a request. A lot of data in this component and the above mentionedHTTP request defaultMany properties in the component are the same, if this sampler is inHTTP request defaultWithin the scope of the component, the empty properties in the sampler will be filled with default values, and the non-empty properties will be overwrittenHTTP request defaultThe same property in the component (nearest).Quick Start for JMeter Interface Testing

Component parameter description:

parameter name Value and meaning
protocol Is it http protocol or https protocol
Server name or IP Domain name or IP address
The port number port number of the server
path the path part in the URL
content encoding The character set encoding used by the HTTP request
parameter HTTP request parameters (query parameters in the URL)
message body data request body data
request method HTTP methods such as GET, POST, PUT, DELETE, etc.
File Upload for uploading files
Automatic redirection Check to indicate automatic redirection. Indicates that the downstream HTTP protocol handler will automatically redirect, so the process of redirection is invisible to JMeter. And can only be used for GET and HEAD methods. POST and PUT methods are rejected.
follow redirect If checked, it means to follow the redirection (only valid when automatic redirection is not checked). If set, JMeter's sampler will process the response, and will track each redirection in the process, and use the last unredirected request and response as the outermost sample data, and other request data as this Additional information for sampled data. (Maximum number of redirects is 20)
Use KeepAlive When checked, JMeter will set the request header Connection: keep-alive . But whether this option takes effect is also related to the HTTP implementation of JMeter

response assertion

Right-click the sampler and click the [Add – Assert – Response Assertion] option to add

The response assertion can assert the result obtained by the sampler, and assert the content including the response header, response code, response body, etc. with logic (equals, inclusion, regular matching, etc.) to verify whether the output of the sampler conforms to the tester's expectations.

Quick Start for JMeter Interface Testing

Component parameter description:

parameter name Value and meaning
Name the name of the assertion
Apply to The main sample only option is generally used to select the scope of the assertion. Main sample refers to the sampler to which the assertion belongs, and sub samples refers to the subsamplers generated by this sampler, such as the advanced HTTP sampler. OPTIONS – Get the built-in resource, which will generate a subsampler.
Field to Test Refers to the target for which the assertion needs to be made. Text Response refers to the entire response obtained from the server as text (response body). Response Code is the response code (eg 200). Response Message is the response message (eg OK). Response Headers are response headers. Request Headers refers to request headers. Request Data refers to all data requested as text (request body). URL sampled is the sampled URL. Document refers to the document extracted with specific rules as in the Document part of the View Results Tree component.
Ignore status The status code of the response is ignored. Generally 4xx and 5xx are considered as failures by default. If not set, the total sample result is a combination of success/failure and asserted results by status code. If it is set, it will set the status to success, and then make an assertion (note: if this parameter is set, put this assertion first, otherwise the failure result of the previous assertion will be cleared)
Pattern Matching Rules What rules to use for a given pattern string. Contains contains pattern strings (pattern strings are treated as regular expressions). Matches means matches for regular matches (pattern strings are treated as regular expressions). Equals means equality (case-sensitive, pattern strings are treated as plain text). Substring indicates that the text under test contains the given pattern string (the pattern string is treated as plain text). Two logical symbols: Not and Or . Not means negate the result. Or indicates that a matching rule for a given sequence of patterns holds an assertion that is OK.
Patterns to Test A list of pattern strings to test against. Multiple pattern strings can be added by clicking the Add button. If it is a regular expression, it is a Perl5-style regular expression without enclosing parentheses.

JSON variable extraction

Right click on the request, Add – Post Processors – Json Extractor to add the JSON extractor element

JSONExtractors can be used to retrieveJSONExtract the attribute at the specified position in the structure as a variable.Quick Start for JMeter Interface Testing

Component parameter description:

parameter name Value and meaning
Name Descriptive name for display
Names of created variables One or more names (comma-separated) of the variables to be created, and the number should correspond to the JSON Path expression
JSON Path Expressions One or more JSON path expressions (multiple separated by commas), the number of which must match the number of variables. (Refer to the following for the writing of the expression)
Default Values One or more default values ​​(multiple separated by commas). If a JSON path expression does not return a value, the default value for the corresponding location is used. The number is the same as the number of variables
Match No. (0 for Random) If the JSON path expression can take multiple values, which one should be taken. 0 means random; -1 means extract all the results (multiple variables will be generated, named _N, N starts from 1); X means extract the results of the specified position, starting from 1, if X is greater than the number of results, return empty (will try to use default value)
Compute concatenation var If checked, it means that if multiple results are obtained, they will be separated by commas and put into a variable named _ALL

JSON pathWriting:$symbol represents the root element,.represents the attribute,[0]means to take the first element of the array object ([1]is the second).

E.g:

{
    "user": {
        "names": ["Jack", "Jacky"],
        "age": 10
    }
}


for the aboveJSON, using the expression$.user.names[0]can be extractedJackthis value. For more detailed information, please refer to:https://jsonpath.com/

View Results Tree Elements

This element is used to useJMeterWhen the interface performs request execution to view the execution status of the request, he can view the requested request message, response message, and assertion information. See below for details.

JMeter usage example

Next, we use the knowledge learned above to implement such a scenario: queryGiteeContributors under the pigtooth fish repository, and then extract a specified contributor name, and use the second request to obtain the contributor's information.

in useGiteeThe two interfaces are

  • GET https://gitee.com/open-hand/choerodon/contributors_count?ref=0.23.0

The structure of the response body is (the name of the contributor we need to getJSON pathfor$.contributors[0].username):

{
    "status": 1,
    "contributors_count": "16",
    "contributors": [
        {
            "username": "example1"
        }
    ]
}


  • GET https://gitee.com/{contributor name}

Create a test plan

Open Jmeter and there will be a default test planQuick Start for JMeter Interface Testing

Create thread group

Right-click the test plan, clickAdd > Threads (Users) > Thread GroupAdd a thread group element. Fill in the following values:Quick Start for JMeter Interface Testing

createHTTPDefault value configuration element

Right-click the thread group,Add > Config Element > Http Request DefaultsAdd configuration elements. Fill in the values ​​as follows:Quick Start for JMeter Interface Testing

createHTTPSampler to get list of contributors

Right click on the thread group,Add > Sampler > HTTP RequestAdd sampler (fill in path and add a parameter):Quick Start for JMeter Interface Testing

Add response extractor

Right click on the request sampler,Add > Post Processors > JSON extractorAdd the element as follows, because some users are ingiteedoes not exist, here we will extractJSON pathfor$.contributors[4].username(that is, the fifth contributor) username value into a variablecontributorNameQuick Start for JMeter Interface Testing

Add the View Results Tree element to the request

Right click on the sampler,Add > Listener > View Results TreeAdd to view the result tree as follows:Quick Start for JMeter Interface Testing

Add toHTTPSampler requests specific contributor information

Right click on the thread group,Add > Sampler > HTTP RequestAdd sampler (herepathattribute fill${contributorName}Used to refer to variables extracted from the previous request):Quick Start for JMeter Interface Testing

Add the View Results Tree element to the request

Right click on the sampler,Add > Listener > View Results TreeAdd to view the result tree as follows:Quick Start for JMeter Interface Testing

Click the green triangle to execute

After clicking the execute button, we will be prompted to save the file before executing it. After selecting a suitable directory to save, click the execute button. At this time, the green execute button will turn gray, and the timing will start in the upper right corner, which indicates that the request is being processed. Execute, when the button turns green again, the execution is over.

Quick Start for JMeter Interface Testing

View execution results

Click on the first requestView Results TreeElements can view the execution result of this request:Quick Start for JMeter Interface Testing

You can see that the information in the response body is:

Quick Start for JMeter Interface Testing

View the request data of the second request, you can see that the request is successful, and you can see the request path${contributorName}already rendered as the value fetched by the first requesthandchoerodonQuick Start for JMeter Interface Testing

Summarize

JMeterprovidedHTTPSamplers, various assertion mechanisms, configuration mechanisms, and variable extraction mechanisms can help with our modular interface testing, making the system more robust.

Extended information

  1. JMeter Get Started
  2. JMeter component description

This article was originally created by the pigtooth fish technical team, please indicate the source for reprinting:Pigtooth fish official website

About Pigtooth

Choerodon's full-scenario performance platform provides systematic methodology and collaboration, testing, DevOps and container tools to help enterprises connect requirements, design, development, deployment, testing and operation processes, and improve management efficiency and quality in one-stop. From team collaboration to DevOps tool chain, from platform tools to systematic methodology, Pigtooth fully meets the needs of collaborative management and engineering efficiency, runs through the entire end-to-end process, and helps team performance faster, stronger and more stable.Click here to try pig tooth fish