Исключение формата чисел в Groovy

Я пытаюсь сравнить ставку налога с продаж 6,75 с моим ожидаемым значением 6,75 в формате строки. Я написал приведенные ниже строки кода Groovy для достижения этой цели, но получаю исключение числового формата и не могу понять, в чем проблема

Groovy Code

def jsonSlurper = new JsonSlurper()
def parsedResponseJson=jsonSlurper.parseText(context.expand('${StandardFinance#Response}'))
def actualSalesTaxRate = parsedResponseJson.CustomerQuoteFinanceResponse.StandardFinanceResponse.Responses[0].StandardPaymentEngineFinanceResponse.paymentWithTaxes.financeItemizedTaxes.salesTax.taxParameters.rate
def actualSalesTaxRate = parsedResponseJson.CustomerQuoteFinanceResponse.StandardFinanceResponse.Responses[0].StandardPaymentEngineFinanceResponse.paymentWithTaxes.financeItemizedTaxes.salesTax.taxParameters.rate
log.info actualSalesTaxRate.size()
actualSalesTaxRate = Float.parseFloat(actualSalesTaxRate)
def expectedSalesTaxRate = "6.75"
log.info expectedSalesTaxRate.size()
expectedSalesTaxRate = Float.parseFloat(expectedSalesTaxRate)
assert expectedSalesTaxRate.toString() == actualSalesTaxRate.toString(),"FAIL --- Sales Tax Rate is different"

JSON Response

{
"CustomerQuoteFinanceResponse": {
    "StandardFinanceResponse": {
        "Responses": [{
            "StandardPaymentEngineFinanceResponse": {
                "class": ".APRNonCashCustomerQuote",
                "RequestID": "1",
                "term": "48",
                "financeSourceId": "F000CE",
                "paymentWithTaxes": {
                    "class": ".FinancePaymentWithTaxes",
                    "amountFinanced": "34523.48",
                    "monthlyPayment": "782.60",
                    "monthlyPaymentWithoutDealerAddOns": 782.6,
                    "financeItemizedTaxes": {
                        "salesTax": {
                            "taxParameters": {
                                "rate": "6.75"
                            },
                            "salesTaxAmount": "2322.61"
                        }
                    }
                }
            }
        }]
    }
}
}

2 ответа

Решение

Вам не нужно конвертировать его в число, так как значение в ответе - строка.

  • определить пользовательское свойство уровня теста EXPECTED_TAX_RATE и предоставить значение как 6.75,
  • в ответе rate является строковым значением
  • в этом конкретном случае нет необходимости создавать дополнительный шаг теста Groovy Script только для проверки / сравнения значения, удаления шага.
  • вместо этого добавьте Script Assertion для остального шага запроса запроса сам с вышеупомянутым кодом.
  • Тем не менее, есть небольшие изменения, необходимо прочитать ответ.

Вот полный Script Assertion

//Check the response is received
assert context.response, 'Response is empty or null'

//Read test case property for expected value as string; this way there is no need to edit the assertion; just change the property value
def expectedTaxRate = context.expand('${#TestCase#EXPECTED_TAX_RATE}')

def json = new groovy.json.JsonSlurper().parseText(context.response)

def actualTaxRate = json.CustomerQuoteFinanceResponse.StandardFinanceResponse.Responses[0].StandardPaymentEngineFinanceResponse.paymentWithTaxes.financeItemizedTaxes.salesTax.taxParameters.rate
log.info "Actual tax rate $actualSalesTaxRate"

//Now compare expected and actual
assert actualTaxRate == expectedTaxRate, 'Both tax rates are not matching'

У вас может возникнуть вопрос, такой как "Оставить о строковых значениях. Как сравнить с числами. Например, monthlyPaymentWithoutDealerAddOns имеет номер, а не строку. Как с этим бороться?

Здесь, когда настраиваемое свойство уровня теста определено как EXPECTED_MONTHLY_PATYMENT и значение как 782.6,

Как уже упоминалось выше, можно прочитать в Script Assertion как показано ниже

def expectedMonthlyPayment = context.expand('${#TestCase#EXPECTED_MONTHLY_PATYMENT}') //but this is string

Вы можете прочитать фактическое значение как:

def actualPayment = json.CustomerQuoteFinanceResponse.StandardFinanceResponse.Responses[0].StandardPaymentEngineFinanceResponse.paymentWithTaxes.monthlyPaymentWithoutDealerAddOns
log.info actualPayment.class.name //this shows the data type

Ожидаемый платеж должен быть преобразован в тип фактического платежа.

def actualPayment = json.CustomerQuoteFinanceResponse.StandardFinanceResponse.Responses[0].StandardPaymentEngineFinanceResponse.paymentWithTaxes.monthlyPaymentWithoutDealerAddOns
log.info actualPayment.class.name //this shows the data type
def expectedPayment = context.expand('${#TestCase#EXPECTED_MONTHLY_PATYMENT}') as BigDecimal
assert actualPayment == actualPayment

С учетом этого JSON (похоже на полный, но с закрывающим синтаксисом):

def s = '''
{"CustomerQuoteFinanceResponse": {"StandardFinanceResponse": {
   "Responses": [   {   
      "StandardPaymentEngineFinanceResponse":       {   
         "class": ".APRNonCashCustomerQuote",
         "RequestID": "1",
         "term": "48",
         "financeSourceId": "F000CE",
         "paymentWithTaxes":          {   
            "class": ".FinancePaymentWithTaxes",
            "amountFinanced": "34523.48",
            "monthlyPayment": "782.60",
            "monthlyPaymentWithoutDealerAddOns": 782.6,
            "financeItemizedTaxes":             {   
               "salesTax":                {   
                  "taxParameters": {"rate": "6.75"},
                      "salesTaxAmount": "2322.61"
}}}}}]}}}
'''

Рассмотрим этот код:

def jsonSlurper = new groovy.json.JsonSlurper()
def json = jsonSlurper.parseText(s)
def response = json.CustomerQuoteFinanceResponse
                   .StandardFinanceResponse
                   .Responses[0]

assert 6.75 == response.StandardPaymentEngineFinanceResponse
                       .paymentWithTaxes
                       .financeItemizedTaxes
                       .salesTax
                       .taxParameters
                       .rate as Float
Другие вопросы по тегам