Karate array field become object when it is return

2019-07-30 14:11发布

问题:

I'm trying to compare response with predefined JSON (expected) generated by JS function.
JS:

    function(fleetId) {
        var result = {};
        result.name = "TestConnection";
        result.fleetId = fleetId;
        result.connectionConfigDefault = { "configParameters": [{ "keyName": "N/A", "value": "testValue" }], "id": 4 }
        return result;
    }

Test:

...
Then match connection.response ==
                                       """
                                           {
                                            connectionConfigDefault: '#(connectionJson.connectionConfigDefault)',
                                            fleetId: '#(connectionJson.fleetId)',
                                            id: '#number',
                                            name: '#(connectionJson.name)'
                                           }
                                       """

JS return:

"connectionConfigDefault": {
    "configParameters": { "0": { "keyName": "N/A", "value": "testValue" } }
    }

instead of expected:

"connectionConfigDefault": { 
"configParameters": [{ "keyName": "N/A", "value": "testValue" }]
}

P.S. I read similar question, but the answer did not help me to solve the problem.

回答1:

you can do 1 thing.. before returning your json in javascript convert it to string using configParameters = JSON.stringify(configParameters) now call this function from feature file, with json variable.

In function "function(fleetId)"

before returning result convert it to string by typing

result = JSON.stringify(result)

here you will call that function from karate

* json fleetId = function(fleetId)
* print fleetId

I hope this will resolve your question



回答2:

Yes there is this weird bug in the JDK that you normally never run into unless you start doing nested arrays in JS: https://github.com/intuit/karate/blob/master/karate-junit4/src/test/java/com/intuit/karate/junit4/demos/js-arrays.feature#L44

The workaround here is to do JSON construction using Karate not JS:

EDIT: see using read() below, instead of "in-line":

# * def conf = { "configParameters": [{ "keyName": "N/A", "value": "testValue" }], "id": 4 }
* def fun = 
"""
function(fleetId) {
    var result = {};
    result.name = "TestConnection";
    result.fleetId = fleetId;
    var conf = read('conf.json');
    result.connectionConfigDefault = conf;
    return result;
}
"""

Since Karate has so many nice ways, why don't you use those:

* def fleetId = 1

* set temp
| path    | value            |
| name    | 'TestConnection' |
| fleetId | fleetId          |
| connectionConfigDefault | { "configParameters": [{ "keyName": "N/A", "value": "testValue" }], "id": 4 } |

* print temp