【Detail】Jmeter installation configuration and basic operation

1. Jmeter environment construction and configuration

1. Jmeter environment construction

安装JDK:https://www.oracle.com/cn/java/technologies/downloads/

安装Jmeter:https://jmeter.apache.org/download_jmeter.cgi

Note: Download JDK, pay attention to the computer operating system and the number of digits; the Jmeter version must match the JDK version; the Jmeter installation path cannot contain Chinese or spaces

2. Basic configuration of Jmeter

(1) Chineseization of Jmeter interface

Permanence: Modify the configuration file jmeter.properties in the bin directory, "language=zh_CN", restart Jmeter

Temporary: menu "Options"->Choose Language->Chinese (Simplified)

(2) Jmeter theme modification

Menu "Options" -> Appearance (choose your favorite theme)

(3) The Chinese characters in the response result will not be garbled

Open the configuration file jmeter.properties in the bin directory, modify "sampleresult.default.encoding=UTF-8", and restart Jmeter


2. The main components of Jmeter and related scopes

  • Sampler: call method to send request
  • Logic Controller: Controls the execution order of the sampler (to be used with the sampler)
  • Preprocessor: Assign values ​​to request parameters
  • Post-processor: extract the value of a specific field in the response
  • Assertion: compare the extracted value with the expected result
  • Timer: simulate real business scenarios
  • Configuration element: Initialize test data
  • Listener: View the results of the script run on the console

Element: A container for multiple similar functional components (similar to a class)

Tuple: implement an independent function in the container (similar to a method)

1. The principle of scope

  • sampler: core, no scope
  • Logic Controller: Only works on samplers and logic controllers in its child nodes
  • Other components:
    • If it is a child node of a sampler, the component only works on its parent node
    • If its parent node is not a sampler, its scope is all other descendant nodes under the parent node of the component (including child nodes, child nodes of child nodes, etc.)

2. Execution sequence of components

Execution order of different elements in the same scope (directory/level/indentation):

  • Configuration Elements - Preprocessor - Timer - Sampler - Postprocessor - Assertion - Listener

Execution order of identical elements in the same scope (directory/level/indent):

  • Execute sequentially from top to bottom

case:

Execution sequence: Timer 1 - Request 1 - Timer 1 - Timer 2 - Request 2 - Timer 1 - Timer 3 - Request 3


3. Configuration and use of Jmeter thread group, HTTP request, and view result tree

1. Thread group

Introduction: Control the set of users that Jmeter uses to execute tests

Classification:

  • setUp thread group: pretest operation, executed before all scripts
  • Ordinary thread group: Execute test cases, there can be 1 or more (parallel/serial)
  • tearDown thread group: after the test operation, all scripts are executed after

parameter:

2. HTTP request

Role: send http and https requests to the server

Location: Select Thread Group -> Right Click -> Add -> Sampler -> HTTP Request

parameter:

3. View the result tree

View request parameters: Request Body (request line + request body)

View the response result: Response Body (response body)


Four, Jmeter parameterization

1. Definition: use different test data and call the same test method for testing

2. Essence: Realize the separation of test data and test methods

3. Implementation method

  • User Defined Variables - Global Variables
  • User Parameters - Assign different parameter values ​​to each user
  • CSV data file settings - file method parameterization
  • function - random data
  • database

(1) User-defined variables

Usage scenario: define global variables

Steps for usage:

  1. Add thread group
  2. Add user-defined variables. Format: variable name - variable value
  3. Add an HTTP request, referencing the defined variable name. Format: ${variable name}
  4. view result tree

(2) User parameters

Usage scenario: For the same set of parameters, when different users visit, different values ​​can be obtained

Steps for usage:

  1. Add a thread group and set the number of threads to n (indicating the number of simulated users)
  2. Add user parameter
    1. Add multiple variable names to the first column
    2. Each subsequent column is the data of a group of users
  3. Add an HTTP request, referencing the defined variable name. Format: ${variable name}
  4. add view result tree

(3) CSV file settings

Usage scenario: When different users or the same user cycles multiple times, different values ​​can be obtained

Steps for usage:

  1. Define CSV data file
  2. Add thread group
  3. Add CSV data file settings
  4. Add an HTTP request, referencing the defined variable name. Format: ${variable name}
  5. add view result tree

(4) Function (take __counter function as an example)

Usage scenario: Automatically generate non-repeating data, so that each user can get different data every cycle, and does not need to be defined in advance

Steps for usage:

  1. Add a thread group, set the number of virtual users and the number of cycles
  2. Generate __counter function
  3. To add HTTP requests, use the __counter function. Format: ${__counter(FALSE,)}
  4. add view result tree

(5) Comparison of 4 parameterization methods

User defined variables:

  • Role: define global variables
  • Limitation: Every time the value is taken (whether it is the same user or not) is a fixed value

User parameters:

  • Function: To ensure that different users can get different values ​​for the same set of parameters
  • Limitation: the same user gets the same value when looping multiple times

CSV data file settings:

  • Function: To ensure that different users and the same user can get different values ​​when they cycle multiple times
  • Limitations: manual setup of test data is required

function:

  • Function: To ensure that different users and multiple cycles can get different values, no need to set in advance
  • Limitation: It cannot be used when the input data has specific business requirements (such as: user name and password when logging in)

Five, Jmeter assertion

1. Definition: Let the program automatically judge whether the expected result is consistent with the actual result

2. Reminder: Jmeter has an automatic judgment mechanism (response status code) at the request return level, but the success of the request does not mean that the result must be correct, so a detection mechanism is needed to improve the accuracy of the test

3. Commonly used assertion methods

  • response assertion
  • JSON assertion
  • duration assertion

(1) Response assertion

  • Response Text: The response text from the server, i.e. the body
  • Response code: the status code of the response, for example: 200
  • Response information: response information, for example: OK
  • Response header: response header information
  • Request header: request header information
  • Sample URL: Request URL
  • document (text): the entire document of the response
  • Ignore Status: Ignore the returned response status code
  • includes: the text contains the specified regular expression
  • match: the entire text matches the specified regular expression
  • Equal: The text of the entire returned result is equal to the specified string (case sensitive)
  • String: The text of the returned result contains the specified string (case sensitive)
  • Negative: reversal
  • Or: If there are multiple test modes, ticking means logic or, unchecking means logic and
  • Test mode: fill in the results you specify (you can fill in more than one)

(2) JSON assertion

Usage scenario: When the response result to the HTTP request is in JSON format, JSON assertion can be used

Steps to use: Add Thread Group -> Add HTTP Request -> Add JSON Assertion Configuration Parameters -> Add View Result Tree View Assertion Results

  • Assert JSON Path exists: the path of the JSON element used for the assertion (actual result)
  • Additional assert value: Select the checkbox if you want to generate an assertion with a certain value
  • Match as regular expression: Use regular expression assertions
  • Expected Value: expected value (expected result)
  • Expect null: Select the checkbox if expect null
  • Invert assertion (will fail if above conditions met): Invert assertion (will fail if above conditions met)

(3) Assertion duration

Function: Check whether the response time of the HTTP request exceeds the required range

Steps to use: Add Thread Group -> Add HTTP Request -> Add Assertion Duration Set Duration -> Add View Result Tree


6. Jmeter association

1. Definition: When there is a dependency between requests, for example, the input parameter of one request is the data returned by another request, then association processing is required

2. Commonly used association methods

  • Regular Expression Extractor
  • XPath extractor
  • JSON extractor
  • JMeter properties

(1) Regular expression extractor

Usage scenario: Response data in any format can be extracted using a regular expression extractor

Steps for usage:

  1. Add thread group
  2. Add HTTP request 1
  3. Add regex extractor settings parameter in postprocessor
  4. Add HTTP request 2, quoting the quoting name in the regex. For example: quote it with ${title}
  5. add view result tree

Regular expression: It is a formula, or a set of rules, which can be used to extract the desired data content from any string

Formula format: left boundary (matching symbol) right boundary: the data content you want to obtain can be extracted

.: is a wildcard character that can represent any character (except line feed and carriage return)

*: Indicates that the previous character appears 0 or more times

.*Matching rules: After finding the left boundary value, look for a boundary to the right, find the last right boundary, and record all the data in the middle

?: 代表非贪婪匹配,找到左边界后,往右查找匹配右边界,只要有匹配的右边界就停止继续查找;再次查找左边界和右边界

公式格式:左边界(.*?)右边界

<title>百度一下,你就知道</title>

<title>(.*?)</title>

(2)xpath提取器

使用场景:针对HTML格式的响应结果数据进行提取

使用步骤:

  1. 添加线程组
  2. 添加HTTP请求1
  3. 在后置处理器中选择添加xpath提取器设置参数
  4. 添加HTTP请求2,引用正则表达式中的引用名称。如:用${title}引用它
  5. 添加查看结果树

  • Use Tidy (tolerant parser):当需要处理的页面是HTML格式时,必须选中该选项;当需要处理的页面是XML或XHTML格式时,取消选中该选项
  • 引用名称:存放提取出的值的参数名称
  • XPath Query:用于提取值的XPath表达式
  • 匹配数字:如果XPath路径查询出许多结果,则可以选择提取哪个
    • 0:表示随机,-1:表示提取所有结果,1表示第一个值
  • 缺省值:参数的默认值

(3)JSON提取器

使用场景:针对JSON格式的响应数据进行提取

使用步骤:

  1. 添加线程组
  2. 添加HTTP请求1
  3. 在后置处理器中选择添加JSON提取器设置参数
  4. 添加HTTP请求2,引用正则表达式中的引用名称。如:用${title}引用它
  5. 添加查看结果树

  • Names of created variables:存放提取出的值的参数名称。如:cit
  • JSON Path expressions:用于提取值的JSON路径表达式
  • Match No:0表示随机;-1表示提取的所有结果,1表示第一个值
  • Default Values:参数的默认值

(4)JMeter属性

使用场景:在不同的线程组之间传递参数

使用步骤:

  1. 添加线程组1
  2. 添加HTTP请求1
  3. 添加提取器(JSON、Xpath、正则表达式)
  4. 添加BeanShell取样器(将取样器提取的值保存为JMeter属性)
    1. 保存JMeter属性:${__setProperty(变量名,${提取器提取出值的变量},)}
  5. 添加线程组2
  6. 添加HTTP请求2(读取JMeter属性)
    1. 读取JMeter属性:${__property(变量名,,)}
  7. 添加查看结果树

Note: __setProperty function execution (JMeter property): needs to be executed through the BeanShell sampler


7. Jmeter automatically records scripts

1. Definition: In old projects without interface documents, quickly record http interface requests generated by web pages to help write interface test scripts

2. Principle: When recording, JMeter acts as a proxy server to intercept and forward request and response data

3. Jmeter script recording steps

(1) Add an HTTP proxy server and configure it (in non-test components)

(2) Open the browser agent of the windows operating system

(3) Start the proxy server and start recording

(4) Operate in the browser page. After success, you can see the captured interface request in JMeter

When using the proxy, it is found that the package cannot be captured, and the following situations may occur:

  • There is a problem with the filter rule setting
  • Restart the Jmeter proxy server or restart Jmeter
  • Use another browser ( Chrome , IE )
  • Check whether the proxy settings in the PC are available
  • Unplug the network cable and capture the packet

8. Jmeter connects to the database

1. The role of direct connection to the database

  • Used as a parameterization for requests. For example: the user name required for login can be queried from the database
  • An assertion to use as a result. For example: when adding a shopping cart to place an order, check whether the order number returned by the interface is consistent with the order number generated in the database
  • Clean up junk data. For example: add a product (product name/number, etc. cannot be repeated), and then execute the script will not succeed, you need to delete the product data before the next execution
  • Prepare test data. For example: prepare a large amount of performance test data through the database

2. Steps to directly connect to the database

(1) Add the Mysql driver jar package

(2) Configure database connection information

Add method: Test Plan -> Thread Group -> Configuration Element -> JDBC Connection Configuration

(3) Add JDBC request

Add method: Test Plan -> Thread Group -> Sampler -> JDBC Request

(4) Use the variable name of the result returned by the SQL statement to replace the original fixed data


Nine, Jmeter common logic controller

1. If (if) controller

Role: if controller is used to control whether the test element below it runs

Location: Test Plan -> Thread Group -> Logic Controller -> IF Controller

2. Loop controller

Function: Control the following test elements to be executed one or more times

Location: Test Plan -> Thread Group -> Logic Controller -> Loop Controller

Note: The thread group can also control the number of loops, but it has a different scope from the loop controller. The loop of the thread group is valid for all HTTP requests under the thread group, and the loop controller is valid for the HTTP requests under the child nodes

3. ForEach controller

Function: Generally used with user-defined variables or regular expression extractors to read a series of related variable values ​​in the returned results. All samplers under this controller will be executed one or more times, each reading a different variable value

Location: Test Plan -> Thread Group -> Logic Controller -> ForEach Controller

For example:

Then subsequent requests will assign values ​​1, 2, and 3 in sequence when using ${kw}


Ten, Jmeter commonly used timer

1. Synchronous timer

Definition: Blocking threads (accumulating certain requests), when a certain number of threads are reached within the specified time, these threads will be released together at the same time point, creating a lot of pressure instantly

Location: Test Plan -> Thread Group -> Add Timer -> Synchronizing Timer

  • The number of simulated user groups: the number of simulated users, that is, the number of threads to be released at the same time. If set to 0, it is equal to the number of threads in the thread group
  • The timeout time is in milliseconds: the timeout time, that is, how many milliseconds after the timeout, the specified number of threads will be released at the same time; if it is set to 0, the timer will wait for the number of threads to reach the set number of threads before releasing, if it does not reach the set number of threads Numbers will always die. If it is greater than 0, then if the set number of threads has not been reached after the set maximum waiting time has passed, the thread that has arrived will be released directly without waiting. Default is 0

It is recommended to set the timeout time, otherwise it will wait forever; it cannot be set too small, otherwise it will be released if the specified number of threads is not reached

2. Constant throughput timer

Definition: Simulate the user's real usage scenario, let Jmeter execute according to the specified throughput, in units of per minute

Location: Test Plan -> Thread Group -> Add Timer -> Constant Throughput Timer

  • Target Throughput: Number of requests sent per minute per user

case:

—Simulate the user's real business scenario requirements: 20 QPS (requests per second)

— If the number of threads is set to 1, the target throughput is set to 20 * 60 = 1200

— If the number of threads is set to 2, the target throughput is set to 20 * 60 / 2 = 600

3. Fixed timer

Definition: Specifies how long a thread waits (in milliseconds)

Location: Test Plan -> Thread Group -> Add Timer -> Fixed Timer


Eleven, Jmeter distributed test

1. Application scenario: When using Jmeter for performance testing, if the number of concurrency is relatively large (for example, the project needs to support 10,000 concurrency), a single computer (CPU and memory) may not be able to support it. At this time, you can use the distributed test provided by Jmeter function of

2. Principle:

  • In distributed testing, it is divided into one control machine (Master) and multiple agent machines (Slaves)
  • The control machine is responsible for sending test tasks to the agent machine
  • The agent machine receives the task and sends a request to the server, receives the response returned by the server, and returns the test result to the control machine
  • The control machine conducts summary statistics on the test result data

3. Precautions

  • All test machine firewalls have been turned off
  • All test machines and servers are in the same network
  • All test machine Jmeter version and JDK version are exactly the same
  • Turn off the RMI SSL switch in Jmeter

 4. Distributed test steps

(1) Agent configuration

  • Jmeter needs to be installed on the agent machine
  • Modify the service port. Note: It is not necessary, if you need to use different ports for demonstration on the same machine, multiple machines do not need to be modified
  • Open the bin/jmeter.properties file and modify 'server_port', for example: ''server_port=2001'
  • Run the jmeter-server.bat file on the agent to start Jmeter

Note: The proxy machine can be multiple Jmeters installed on your own computer, or it can be Jmeters on other computers

(2) Controller configuration

  • Modify the jmeter.properties configuration file in Jmeter's bin directory, and modify 'remote_hosts'
    • Example: 'remote_hosts=192.168.182.100:1099,192.168.182.200:2099'
    • IP and Port are the IP of the proxy machine and the custom port, separated by "," between multiple proxy machines
  • Start Jmeter
  • Select the menu: Run-->Remote Start/Remote Start All

12. Jmeter generates graphical reports

1. Application scenario: In Jmeter, the script running results can be displayed graphically (pie chart, histogram...), which is more intuitive than the aggregation report or view result tree component, and the user experience is better

2. How to use

命令:jmeter -n -t 脚本文件 -l 日志文件 -e -o 目录

-n 无图形化运行
-t 被运行的脚本
-l 将运行信息写入日志文件
-e 生成测试报告
-o 指定报告输出目录

Notice:

1. The script file must specify a directory or place the script file in the bin directory of jmeter

2. Log files and directories can be left blank, and they are in the current directory by default; if filled in, the files and directories must be empty

3. Example

Guess you like

Origin blog.csdn.net/ouihsiad/article/details/128281922