Jmeter-仅在请求或断言失败时打印日志

Jmeter- Print log only when request or assertion fails

以下是 JSR223 断言 groovy 代码,我们仅在请求或断言失败或两者都失败时才尝试记录。

import groovy.json.JsonSlurper

String jsonString = SampleResult.getResponseDataAsString();
String StartProcessResponseCode= SampleResult.getResponseCode();
def tokenJSON = new JsonSlurper().parseText(jsonString)

if (!SampleResult.isSuccessful()) {
 log.info("Failed Response Data---------"+SampleResult.getResponseDataAsString())
 }

String status= tokenJSON.status

assert StartProcessResponseCode.equals("200")
assert "SUCCESS".equals(status)

for (a in SampleResult.getAssertionResults()) {
  if (a.isError() || a.isFailure()) {
  //log.error(Thread.currentThread().getName()+": "+SampleLabel+": Assertion 
  failed for response: " + new String((byte[]) ResponseData));
  log.info("Failed Assertion Message---------------------"+AssertionResult.getFailureMessage());
  log.info("Failed Response Data---------------------"+SampleResult.getResponseDataAsString())
}

}

但在这种情况下,错误不会记录任何断言失败

首先,如果您想捕获有关断言的所有信息,您应该选择 JSR223 Listener instead, as per JMeter Test Elements Execution Order 侦听器在断言之后执行,这样可以保证您在检查之前应用所有断言。

关于问题本身,我的预期是您的断言逻辑在 assert 语句上失败,这些语句抛出未处理的 AssertionError 并且您的测试根本无法继续

参见以下示例:

log.info('Assertion Start')
assert 'foo'.equals('bar')
log.info('Assertion Ended')

根据您实施的内容,您应该会在 jmeter.log 文件中看到 Assertion Ended 消息,但是它永远不会发生,因为 assert 失败

如果您修改代码以捕获 AssertionError,例如:

log.info('Assertion Start')
try {
    assert 'foo'.equals('bar') : "Failure here"
}
catch (AssertionError e) {
    log.info(e.getMessage())
}
log.info('Assertion Ended')

您将同时看到 AssertionError messageAssertion Ended 声明

有关在 JMeter 中使用 JSR223 断言的更多信息,请参阅 Scripting JMeter Assertions in Groovy - A Tutorial