jmeter添加自定义扩展函数之if判断
1,打开eclipse,新建maven工程,在pom中引用jmeter核心jar包,具体请看---https://www.cnblogs.com/guanyf/p/10863033.html---,这里就不再赘述
2,代码如下:
1 package com.mytest.functions; 2 3 4 5 import org.apache.jmeter.engine.util.CompoundVariable; 6 7 import org.apache.jmeter.functions.AbstractFunction; 8 9 import org.apache.jmeter.functions.InvalidVariableException; 10 11 import org.apache.jmeter.samplers.SampleResult; 12 13 import org.apache.jmeter.samplers.Sampler; 14 15 import org.apache.jmeter.threads.JMeterVariables; 16 17 18 19 import java.util.Collection; 20 21 import java.util.LinkedList; 22 23 import java.util.List; 24 25 26 27 public class If extends AbstractFunction { 28 29 private static final List<String> desc = new LinkedList<String>(); 30 31 private static final String KEY = "__if"; 32 33 34 35 static { 36 37 desc.add("Actual value"); 38 39 desc.add("Expected value"); 40 41 desc.add("Result if actual == expected"); 42 43 desc.add("Result if actual != expected"); 44 45 desc.add("Name of variable in which to store the result (optional)"); 46 47 } 48 49 50 51 private Object[] values; 52 53 54 55 public If() { 56 57 } 58 59 60 61 @Override 62 63 public synchronized String execute(SampleResult previousResult, Sampler currentSampler) 64 65 throws InvalidVariableException { 66 67 68 69 String actual = getParameter(0); 70 71 String expected = getParameter(1); 72 73 74 75 String result = null; 76 77 if (actual.equals(expected)) { 78 79 result = getParameter(2).toString(); 80 81 } else { 82 83 result = getParameter(3).toString(); 84 85 } 86 87 88 89 JMeterVariables vars = getVariables(); 90 91 if (vars != null && values.length > 4) { 92 93 String varName = getParameter(4).trim(); 94 95 vars.put(varName, result); 96 97 } 98 99 100 101 return result; 102 103 } 104 105 106 107 @Override 108 109 public synchronized void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { 110 111 checkMinParameterCount(parameters, 4); 112 113 values = parameters.toArray(); 114 115 } 116 117 118 119 @Override 120 121 public String getReferenceKey() { 122 123 return KEY; 124 125 } 126 127 128 129 @Override 130 131 public List<String> getArgumentDesc() { 132 133 return desc; 134 135 } 136 137 138 139 private String getParameter(int i) { 140 141 return ((CompoundVariable) values[i]).execute(); 142 143 } 144 145 }