Modified variable name in karate framework

Viewed 181

I want to modified param variable for my request(GET/POST) dynamically. As I have 2 different environment which takes different parameters for same request. I tried below code, but not able to replace param variable(name). I can replace param value successfully.

This function generate the dynamic param name for different enviornment

public static String paramDynamicVariable(String env, String param) {
    String paramValue;

    if (env.equals("test")) {
        paramValue =  '$' + param;
    } else {
        paramValue = param;
    }
    return paramValue;
}

Now when I am using paramValue in my test--

Scenario: xyz
Given path URLOfRequest
* print paramDynamicVariable(karate.env,'nameParam')
And param random.paramDynamicVariable(karate.env,'nameParam') = 10

It prints correct value, but in the next line it is not replacing for param name. Please suggest if any solution is there to dynamic param name.

1 Answers

Please do something like this:

* def nameParam = paramDynamicVariable(karate.env, 'nameParam')
* def paramValues = {}
* paramValues[nameParam] = 10

And then:

* params paramValues

Since params accepts any JSON, all you need to do is create the JSON. Since the key is dynamic, it requires you to do a little more work.

Related