我在JMeter中有一个很大的Groovy脚本,我希望在脚本的不同位置重用一些方法。下面是我尝试过的。
这是一个普通的脚本,我编写了一个要从Jmeter调用的函数。
Tools.groovy
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$raw_payload = file_get_contents('php://input');
$payload = json_decode($raw_payload, true);
if (is_array($payload)) {
$fh = fopen("log.txt", "a+");
if ($fh) {
fwrite($fh, date('Y-m-d H:i:s', time()).PHP_EOL);
fclose($fh);
} else {
trigger_error("Unable to open file!");
}
} else {
trigger_error("Invalid payload!");
}
} else {
trigger_error("Invalid request!");
}
下面是我调用该函数的JMeter Groovy代码。
public void AssertValuesF(float Expected, float Actual, String PassMessage, String FailureMessage){
if(Expected==Actual){
log.info("****Assertion Successful****");
log.info("Actual: "+Actual+" Expected: "+Expected +"\n");
log.info(PassMessage);
}
else{
vars.put("AssertionFailure","true");
AssertionResult.setFailure(true);
vars.put("FailureMsg",vars.get("FailureMsg") + "\n****ASSERTION FAILURE****** \n"+FailureMessage + " || EXPECTED: "+ Expected + " || ACTUAL: "+Actual + "\n");
log.info("****ASSERTION FAILURE******");
// AssertionResult.setFailureMessage("****Assertion Failure****** "+FailureMessage + " Expected: "+ Expected + " Actual: "+Actual+"\n");
log.info(FailureMessage);
log.info("Actual: "+Actual+"Expected: "+Expected);
}
}
输出显示此错误 File sourceFile = new File("D://TestScript//Tools.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();
myObject.AssertValues("s","s","asdf","asdf");
这可能是因为Groovy无法提供'log'对象。我该如何解决这个问题?
答案 0 :(得分:2)
log
速记仅适用于JSR223 Elements,为了能够使用它,您需要像在JSR223TestElement类中所做的那样手动定义它
因此将您的代码修改为:
import org.slf4j.Logger
import org.slf4j.LoggerFactory
public void AssertValuesF(float Expected, float Actual, String PassMessage, String FailureMessage) {
final Logger log = LoggerFactory.getLogger(getClass());
if (Expected == Actual) {
log.info("****Assertion Successful****");
log.info("Actual: " + Actual + " Expected: " + Expected + "\n");
log.info(PassMessage);
} else {
vars.put("AssertionFailure", "true");
AssertionResult.setFailure(true);
vars.put("FailureMsg", vars.get("FailureMsg") + "\n****ASSERTION FAILURE****** \n" + FailureMessage + " || EXPECTED: " + Expected + " || ACTUAL: " + Actual + "\n");
log.info("****ASSERTION FAILURE******");
// AssertionResult.setFailureMessage("****Assertion Failure****** "+FailureMessage + " Expected: "+ Expected + " Actual: "+Actual+"\n");
log.info(FailureMessage);
log.info("Actual: " + Actual + "Expected: " + Expected);
}
}
您将可以通过Groovy脚本使用它:
还请注意,有groovy.utilities
属性可用于重复使用__groovy() function中的自定义脚本,您需要将下一行添加到 user.properties 文件:
groovy.utilities=D:/TestScript/Tools.groovy
或通过-J
command-line argument传递,例如:
jmeter -Jgroovy.utilities=D:/TestScript/Tools.groovy -n -t test.jmx -l result.jtl
参考文献: