groovy 的 JMeter 断言失败

JMeter Assertion failure with groovy

更新: 我想查看一份关于他的结构的 JSON 文档。我用语言 groovy 创建了一个 JSR223 断言。我检查 JSON 结构的代码如下所示:

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());

JMeter 日志文件中的验证效果很好。 但是在我的查看结果树中,我收到以下错误消息:

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

我想看看测试结果是否成功

如何解决这个问题?

  1. 不要实例化AssertionResult class,它是预定义的

  2. 不要使用Groovy assert keyword它不会像预期的那样使父采样器失败, 请参考下面的示例简单代码

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

    一旦你像下面这样工作:

    您可以根据需要开始修改测试

请参阅 How to Use JMeter Assertions in Three Easy Steps 指南以了解有关在 JMeter 测试中使用断言的更多信息。