在接口测试过程中,经常会遇到枚举值,如果接口传参数,想随机取某一个枚举值应该怎么办呢?

本人结合实际工作中的需求,编写了一个jmeter函数,输入枚举值,枚举值中间以英文符号","进行区分,然后枚举值的随机值。

代码如下:

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

public class randomStringList extends AbstractFunction{
    private static final String KEY = "__RandomStringList";//这里是函数名,也就是在函数助手列表中显示的名称
    
    private static final List<String> desc = new ArrayList<>();
    private Object[] values;
    
    //函数助手中需要传的参数
    static {
        desc.add("please enter your String,(use , as separator)");
    }

    @Override
    public List<String> getArgumentDesc() {
        // TODO Auto-generated method stub
        return desc;
    }
    
    //对输入的字符串进行切分,通过","来进行分割成List
    public static ArrayList<String> StringToList(String stringList) {
        ArrayList<String> strList = new ArrayList<String>();
        final String DELIMITER = ",";    
        for (String s:stringList.split(DELIMITER)) {
            strList.add(s);
        }    
        return strList;
    }
    
    //调用StringToList方法,获取ArrayList,然后对StringToList进行随机取值,并返回
    @Override
    public String execute(SampleResult arg0, Sampler arg1) throws InvalidVariableException {
        String stringList = ((CompoundVariable) this.values[0]).execute().trim();
        ArrayList<String> strList = StringToList(stringList);
        String str = null;
        Random random = new Random();
        for(int i=0;i<strList.size();i++) {
            int index = random.nextInt(strList.size());
            str = strList.get(index);
        }
        return str;
    }

    @Override
    public String getReferenceKey() {
        
        return KEY;
    }

    @Override
    public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
        checkMinParameterCount(parameters, 1);
        this.values = parameters.toArray();    
    }

}