---
title: JMeter If Controller
url: https://blog.octoperf.com/jmeter-if-controller/
date: '2019-03-28'
authors:
- jloisel
categories:
- JMeter
tags:
- JMeter
- Controller
- Groovy
description: Use Advanced logic in your scripts with JMeter If Controller. Design Dynamic JMeter Thread Groups thanks to this logic action.
---

# JMeter If Controller

You may ask yourself:

- How can I script Thread groups with **dynamic behavior**?
- How to use the JMeter If Controller to leverage conditional behavior?

Good News! We're going to show you the [JMeter If Controller](https://jmeter.apache.org/usermanual/component_reference.html#If_Controller) by introducing you to conditional statements, advanced conditions and performance considerations.

## Use-Cases

The If Controller works great when you need to execute some elements of the Thread Group based on a given state. Let me give you meaningful examples:

- If `the shopping cart is empty`, then execute `Add a New Product to Cart`,
- If `Account balance is below Zero`, then `Issue a wire transfer to rebalance the Account`.

Depending on a given `condition`, then a given `action` is taken. That's it!


## Configuration

As defined in Apache JMeter Documentation:

>  The If Controller allows the user to control whether the test elements below it (its children) are run or not. By default, the condition is evaluated only once on initial entry, but you have the option to have it evaluated for every runnable element contained in the controller.

In programming, If Statement is a [Conditional statement](https://en.wikipedia.org/wiki/Conditional_(computer_programming)#If%E2%80%93then(%E2%80%93else)). It basically means: **if something is true, then do this**. That's as simple as that!

The true power of the if controller resides in its capability to unleash complex conditions to control the Thread Group execution flow.

![JMeter If Controller](https://blog.octoperf.com/img/blog/jmeter-if-controller/jmeter-if-controller.png "JMeter If Controller UI")

Let's dive into the possible settings:

- **Name**: the name of the controller. Give it a relevant name for better understanding of what it does. Example: *IfExpensesAreHigh*,
- **Condition** (required): the condition language is [Javascript](https://en.wikipedia.org/wiki/JavaScript) by default. This is the heart of the If controller. Example: `${count} == '0'`,
- **Interpret Condition as Variable Expression**: If this is selected, then the condition must be an expression that evaluates to `true` (case is ignored). Which means the conditions must output the `true` string to be recognized as true,
- **Evaluate for all children**: means the conditions is evaluated each time a child element is executed.

You're possibly a bit lost with all those settings. It's normal! Just **focus on the condition** for now.

## Simple Conditions

Let's go right to the interesting thing! Let's see some real-world simple conditions that work:

- `1==1`: always evaluates to true,
- `“${JMeterThread.last_sample_ok}”`: checks if the last request was successful,
- `"${my_variable}" == "1"`: checks if `my_variable` variable is equal to `1`,
- `${__jexl3(${COUNT} == "1",)}`: checks if `COUNT` variable is equal to `1` using Jexl3,
- `${__groovy("${COUNT} == "1")}`: checks if `COUNT` variable is equal to `1` using Groovy.

Great! We have seen some very simple examples. See our documentation For further [examples and common mistakes using If](https://api.octoperf.com/doc/design/edit-virtual-user/action-types/logic-actions/if-action/#common-mistakes).

## Comparison Operators

The following operators allow to compare numeric values:

- `==`:  Left value must be equal to right value,
- `!=`:  Left value must be different than right value,
- `<=`:  Left value must be inferior or equal to right value,
- `>=`:  Left value must be superior or equal to right value,
- `<`: Left value must be inferior to right value,
- `>`: Left value must be superior to right value.

It's especially useful when you need to check numeric values against each other. Example: `"${salary}" >= "2000"`.

## Boolean Operators

In some case, you want to check multiple variables at the same time. In this case, you may take a look at the following examples:

- `(${__threadNum} ==1 || ${__threadNum} % 5 == 0) && ${__iterationNum} == 1`: checks if it's the first thread, or if thread number is a multiple of 5 AND if it's the first iteration.

Multiple Conditions are liked using the following boolean operators:

- `&&`: equivalent to `and`,
- `||`: equivalent to `or`.

Also, parenthesis `(` and `)` help to control the priority between the operators.

It may be useful to install [Custom JMeter Functions](https://jmeter-plugins.org/wiki/Functions/) plugin, via the [JMeter Plugins Manager](https://jmeter-plugins.org).

![JMeter Functions Plugin](https://blog.octoperf.com/img/blog/jmeter-if-controller/jmeter-functions-plugin.png "JMeter Functions plugin")

## Common Syntax Errors

I'm sure you've already had issues writing If conditions properly. I did! It's very common to make syntax mistakes and it can takes minutes to hours to find them out.

- `${cart_status} != "PROCESSING"`: should be `"${cart_status}" != "PROCESSING"`,
- `${loginOK} != "NotFound"`: should be  `"${loginOK}" != "NotFound"`,
- `${myvar} <= "10"`: should be `${myvar} <= 10`
- `"${loginOK}" != "Notfound"`: should be `"${loginOK}" != "NotFound"` with an uppercase 'F',
- `${login_${count}} != "NotFound"`: should be `${_V(login${count})} != "NotFound"`,
- `${counter}<=5`: should be `${__javaScript(vars.get("counter")<=5)}`.

These are frequent errors we're seeing almost everyday. Just remember it's easy to mess up if conditions and hard to spot them.

## Groovy And Jexl

![JMeter If Performance](https://blog.octoperf.com/img/blog/jmeter-if-controller/jmeter-if-performance.png "If Controller Performance Penalty")

It's recommended to use [Jexl3](https://jmeter.apache.org/usermanual/functions.html#__jexl3) or [groovy](https://jmeter.apache.org/usermanual/functions.html#__groovy) functions to **dramatically improve if condition performance**.

This is why it's recommended to enable `Interpret Condition as Variable Expression?` ([enabled by default in JMeter 3.4](https://bz.apache.org/bugzilla/show_bug.cgi?id=61675)).

If Controller will internally use *javascript* to evaluate the condition. Sadly, this can have a huge impact on performances. `Javascript` interpretation is known to be very slow in JMeter. This is why we're going to see how to optimize If Controller conditions.

## If Else Behavior

Sadly, there is no `Else` block in JMeter, you have only `If`. You need to use **two IF Controllers with opposite conditions**. Here is an example:

- First If condition: `${JMeterThread.last_sample_ok}`,
- Second If (equivalent to Else) condition: `${JMeterThread.last_sample_ok} == false`.

I agree, it's a little bit weird. But, there is no other solution out there. In the case the condition is pretty complex, I would suggest to evaluate it in a [JSR223 script](https://blog.octoperf.com/reusable-sample-jmeter-scripts/) before the 2 ifs, and put the result in a variable (`vars.put("name", value)`).

Then, simply use the variable in the 2 Ifs like in the example above.

## Nullity Checks

JMeter variables are never `null`. In fact, the variable is either defined or it's not. Suppose your variable is named `depdate`:

- If `${depdate}` variable is set, it will be variable value,
- If `${depdate}` variable is not set, it will be default value (which is `${depdate}`).

To check if the variable is set, you can use a groovy condition for example: `${__groovy(vars.get("depdate") != null)}`.

![JMeter If Nullity Check](https://blog.octoperf.com/img/blog/jmeter-if-controller/jmeter-nullity-check.png "Checking if a variable is defined")

## Debugging

When you are completely stuck and nothing above helps, the last resort solution is to debug the if controller condition evaluation.

The easiest way of debugging If Controller is enabling logging for it, you can do it in 2 ways:

- From JMeter GUI having the If Controller selected choose `Help -> Enable Debug`,

![JMeter UI Enable Debug](https://blog.octoperf.com/img/blog/jmeter-if-controller/jmeter-enable-debug.png "Enable JMeter Debug Mode")

- Or by adding the next line to `log4j2.xml` file (in JMeter's `bin` folder):

```xml
<Logger name="org.apache.jmeter.control.IfController" level="debug" />
```

In both cases, the output will be displayed in JMeter logs. 

![JMeter Logs](https://blog.octoperf.com/img/blog/jmeter-if-controller/jmeter-logs.png "JMeter Logs display the If controller statement evaluation result.")

In addition to logs, The [Debug Sampler](https://jmeter.apache.org/usermanual/component_reference.html#Debug_Sampler) can be used:

> The Debug Sampler generates a sample containing the values of all JMeter variables and/or properties.

With all these tools, you should master the JMeter If Controller in no time!
