Why operator '+' inside functions does not

2019-08-04 01:35发布

问题:

I'm trying to process a list of json-s that I got as an answer from an API.

[
  {
    "originalEstimate": "16h",
    "remainingEstimate": "9h",
    "timeSpent": "7h"
  },
  {
    "originalEstimate": "64h",
    "remainingEstimate": "63h",
    "timeSpent": "1h"
  }
]

I have to sum the fields and I came up with a code for it, but it seems like it does not modify the mySum variable.

For this example, I just used the 'originalEstimate'.

I tried to add manually the elements and that works. Ex.: (parseFloat(getNum(json[0].originalEstimate))) == 16.0

getNum is a function that cuts the 'h' down from the string.

The code looks like this:

    * def getNum = function (a)  {return a.substring(0,a.length()-1)}
* text raw =
    """
  [
    {
      "originalEstimate": "16h",
      "remainingEstimate": "9h",
      "timeSpent": "7h"
    },
    {
      "originalEstimate": "64h",
      "remainingEstimate": "63h",
      "timeSpent": "1h"
    }
  ]
  """
    * json json = raw
    * def mySum = 0
    * def fn = function(x) {mySum = mySum + (parseFloat(getNum(x.originalEstimate)))}
    * eval karate.forEach(json,fn)
    * print mySum

I expected to see 80.0 as originalEstimate sum but I received 0. Also, it runs perfectly, just does not modify the mySum

回答1:

Yes, when you declare a function, variables are locked to the value at the time the function was declared. The solution is use karate.get() and karate.set():

* def getNum = function(x){ return x.substring(0, x.length() - 1) }
* def sum = 0
* def fun = function(x){ var temp = karate.get('sum') + parseFloat(getNum(x.originalEstimate)); karate.set('sum', temp) }
* def response =
"""
[
  {
    "originalEstimate": "16h",
    "remainingEstimate": "9h",
    "timeSpent": "7h"
  },
  {
    "originalEstimate": "64h",
    "remainingEstimate": "63h",
    "timeSpent": "1h"
  }
]
"""
* eval karate.forEach(response, fun)
* print sum


标签: java json karate