Search code examples
jmeterperformance-testingbeanshell

JMeter BeanShell Assertion: Getting error when convert String to Long


Have a need to change the value from String to Long in BeanShell Assertion to do verification.

First Apporach

long balance_after_credit = Long.parseLong(String.valueOf("${balance_after_credit_from_db}"));   

Second Approach

long balance_after_credit = Long.parseLong(vars.get("balance_after_credit_from_db"));

For instance, consider am getting a value as '743432545' for the variable balance_after_credit_from_db.

Error

org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval    Sourced file: inline evaluation of: ``long token_balance_after_credit = Long.parseLong(vars.get("token_balance_after_c . . . '' : Typed variable declaration : Method Invocation Long.parseLong

Weird thing is sometimes, I didn't get errors and the script is getting passed. Can anyone please point out where am doing a mistake. TIA.


Solution

    1. Inlining JMeter variables into code-based scripts is not something recommended so go for 2nd approach.

    2. How do you know that exactly String is being returned from the database all the time? It easily can be any other object type, in fact any of described in the Mapping SQL and Java Types article. The way more safe approach will be something like:

      if (vars.getObject("balance_after_credit_from_db") instanceof String) {
          long balance_after_credit = Long.parseLong(vars.get("balance_after_credit_from_db"));
      } 
      else {
          log.error("Unexpected \balance_after_credit_from_db\" variable type");
          log.error("Expected: String, Actual: " + vars.getObject("balance_after_credit_from_db").getClass().getName());
          throw new Exception("Unexpected variable type");
      }
      

      So in case of non-String JDBC query result you will be able to see the relevant message in jmeter.log file

      JMeter variable type

    See Debugging JDBC Sampler Results in JMeter article for more information on working with the entities coming from databases in JMeter tests