Dotan Raz
Dotan Raz

Reputation: 453

How to create simple counter using Beanshell?

I'm trying to create a simple counter that will print the iteration number to the log. the problem is that I didn't find a way to initialize the int value of i to 0. if I'll do it inside the Beanshell script it will keep initializing, I need it to run only once at the beginning of the test. My code:

int i=0;
log.info(string.valueOf(i));
i=i+1;

Upvotes: 1

Views: 1873

Answers (2)

Dmitri T
Dmitri T

Reputation: 168072

It is recommended to avoid scripting where possible, and if you cannot live without scripting you should be using the most performing option which is JSR223 Test Elements and Groovy language.

Particularly your case can be implemented without any scripting, you can use the following JMeter Functions:

  • __log() - which prints an arbitrary message to jmeter.log file
  • __iterationNum() - which returns the number of current iteration

So if you use the statement like: ${__log(Current iteration is: ${__iterationNum},,,)} JMeter will return it where the function is called and additionally print the corresponding message to the log file.

Demo:

JMeter IterationNum Function Demo

You can install __iterationNum() function as a part of Custom JMeter Functions bundle using JMeter Plugins Manager

JMeter Custom Functions Plugins Manager

Upvotes: 1

Ori Marko
Ori Marko

Reputation: 58772

Add Once Only Controller, under it JSR223 Sampler with the initialization

vars.putObject("i", 0);

Then you can increment it after it (not under the Controller) with other JSR223 Sampler:

myI = vars.getObject("i")
log.info(String.valueOf(myI));
vars.putObject("i", ((Integer)myI+1));

Upvotes: 2

Related Questions