Функции и переменные JMeter
Изучите встроенные функции JMeter и пользовательские переменные для повышения гибкости сценариев
«Функции и переменные JMeter» — бесплатный урок Load Testing & Performance Benchmarking (JMeter & k6) на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Load Testing & Performance Benchmarking (JMeter & k6), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Load Testing & Performance Benchmarking (JMeter & k6) содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Dynamic Data in JMeter
Welcome! In performance testing, it's rare for all users to do the exact same thing or use the exact same data.
To simulate real-world scenarios, your test scripts need to be flexible and dynamic. This lesson explores how to achieve this using JMeter's built-in functions and user-defined variables.
What are JMeter Variables?
A JMeter Variable is a placeholder that stores a value. Think of it like a temporary name tag for a piece of information.
- They make your test scripts more readable.
- They allow you to reuse values throughout your test plan.
- Changing a value once updates it everywhere it's used.
This is crucial for maintainability and flexibility.
User Defined Variables (UDVs)
The simplest way to create variables in JMeter is using the User Defined Variables element.
You can add this element under your Test Plan or a Thread Group. Here, you define a variable name and its corresponding value.
This is perfect for static values you want to manage centrally, like a base URL or a default username.
Add Element:
Test Plan > Add > Config Element > User Defined Variables
Configuration:
Name: BASE_URL
Value: http://example.com
Name: USER_COUNT
Value: 100Using UDVs in Requests
Once defined, you can reference your User Defined Variables anywhere in your test plan using the syntax ${variableName}.
JMeter will replace this placeholder with the actual value of the variable during test execution.
HTTP Request Sampler:
Protocol: http
Server Name or IP: ${BASE_URL}
Path: /login
HTTP Header Manager:
Name: X-User-Count
Value: ${USER_COUNT}Introducing JMeter Functions
While variables store fixed or manually updated values, JMeter Functions generate dynamic values during runtime.
Functions start with ${__functionName(...)} and can take parameters. They help simulate more realistic user behavior, like generating random numbers or unique IDs.
The __Random Function
The __Random function generates a random integer within a specified range.
Its syntax is ${__Random(min, max, variableName)}:
min: The smallest number to generate.max: The largest number to generate.variableName: (Optional) A variable to store the generated value.
This is great for picking random items from a list or simulating varying input.
Example:
${__Random(1, 10,)}
// Generates a random number between 1 and 10
${__Random(100, 999, myRandomID)}
// Generates a random number between 100 and 999
// and stores it in a variable named 'myRandomID'Using __Random in a Test
Let's say you want to simulate users accessing random product IDs on an e-commerce site. You can use __Random directly in your HTTP Request path.
This helps distribute the load across different resources, mimicking real user behavior.
HTTP Request Sampler:
Protocol: http
Server Name or IP: ${BASE_URL}
Path: /products/${__Random(1001, 2000,)}
// This would access paths like:
// /products/1543
// /products/1987
// etc.The __counter Function
The __counter function generates a sequence of unique numbers. It's useful when you need to provide unique identifiers or sequential data.
Its syntax is ${__counter(true/false, variableName)}:
true: Counter is global across all thread groups.false: Counter is local to each thread.variableName: (Optional) A variable to store the generated value.
Example:
${__counter(false,)}
// Generates 1, 2, 3... for each thread independently
${__counter(true, globalCount)}
// Generates 1, 2, 3... globally across all threads
// and stores it in 'globalCount'Using __counter for Unique IDs
Imagine you're testing an order creation API where each order needs a unique ID. Using __counter ensures that every request sends a distinct order ID.
This is vital for avoiding data conflicts and accurately simulating transactions.
HTTP Request Sampler:
Method: POST
Path: /orders
Body Data:
{
"orderId": "ORDER-${__counter(true,)}",
"customerName": "Test User"
}
// Example Body Data:
// {"orderId": "ORDER-1", ...}
// {"orderId": "ORDER-2", ...}Functions & Variables Quiz
Which of the following statements about JMeter variables and functions are TRUE?
Recap: Functions & Variables
Great job! You've learned how to make your JMeter tests more dynamic and realistic:
- JMeter Variables provide placeholders for reusable values like base URLs.
- User Defined Variables (UDVs) are a simple way to define these static variables.
- JMeter Functions generate values dynamically during test runtime.
- The
__Randomfunction creates random numbers for varied inputs. - The
__counterfunction generates unique, sequential numbers.
Mastering these will significantly improve the flexibility and accuracy of your load tests!
Часто задаваемые вопросы
Урок «Функции и переменные JMeter» бесплатный?
Да — полный текст урока «Функции и переменные JMeter» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Load Testing & Performance Benchmarking (JMeter & k6), подпишись на CoddyKit PRO. Курс Load Testing & Performance Benchmarking (JMeter & k6) содержит 4 уроков всего.
Чему я научусь в уроке «Функции и переменные JMeter»?
Изучите встроенные функции JMeter и пользовательские переменные для повышения гибкости сценариев Ты практикуешь Load Testing & Performance Benchmarking (JMeter & k6) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Load Testing & Performance Benchmarking (JMeter & k6)?
Предыдущий опыт не требуется. Load Testing & Performance Benchmarking (JMeter & k6) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Функции и переменные JMeter»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Load Testing & Performance Benchmarking (JMeter & k6)?
Да. Каждый урок Load Testing & Performance Benchmarking (JMeter & k6) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Параметризация с данными CSV
- Работа с динамическими значениями (корреляция)
- Функции и переменные JMeter
- Тестирование баз данных с JDBC