fcb1900
fcb1900

Reputation: 359

JMeter Assertion failure with groovy

Update: I want to check a JSON document on his structure. I created a JSR223 Assertion with language groovy. My code to check the JSON structure looks like this:

import groovy.json.*;
import org.apache.jmeter.samplers;

def response = prev.getResponseDataAsString();
log.info("Response" + response);
def json = new JsonSlurper().parseText(response);

//tests
def query = json.query;
assert query instanceof String;

def totalResults = json.totalResults;
assert query instanceof Integer;

def from = json.from;
assert from instanceof Integer;

def to = json.to;
assert to instanceof Integer;

assertionResult = new AssertionResult("Assertion failed! See log file.");
assertionResult.setError(true);
assertionResult.setFailureMessage(e.toString());

The validation in the JMeter logfile works great. But in my View Result Tree, i got the following error message:

Assertion error: true
Assertion failure: false
Assertion failure message: javax.script.ScriptException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script27.groovy: 2: unable to resolve class org.apache.jmeter.samplers
 @ line 2, column 1.
   import org.apache.jmeter.samplers;
   ^

Script27.groovy: 21: unable to resolve class AssertionResult 
 @ line 21, column 19.
   assertionResult = new AssertionResult("Assertion failed! See log file.");
                     ^

2 errors

I want to see if the test result is successful or not.

How to fix this issue?

Upvotes: 1

Views: 4238

Answers (1)

Dmitri T
Dmitri T

Reputation: 168157

  1. Don't instantiate AssertionResult class, it is pre-defined

    JSR223 Assertion Result

  2. Don't use Groovy assert keyword, it won't fail the parent sampler as expected, refer below example simple code

    if (1 != 2) {
        AssertionResult.setFailure(true)
        AssertionResult.setFailureMessage("1 is not equal to 2")
    }
    

    once you get it working like below:

    JSR223 Assertion sample

    you can start modifying your tests as required

See How to Use JMeter Assertions in Three Easy Steps guide to learn more about using assertions in JMeter tests.

Upvotes: 2

Related Questions