IllegalArgumentException error when getting the null response from Json

944 Views Asked by At

I am using Groovy for creating an automation script for parsing the response data from api and updating in my excel test data file. It is working correctly but for certain data there is no response from api so it throws the java.lang.IllegalArgumentException: The JSON input text should neither be null nor empty. exception, which halts the whole process of writing on the excel file. Here is my code guys.

import groovy.json.JsonSlurper
import jxl.*
import jxl.write.*

//define the test case where TestCaseOne is the name of your test case
def myTestCase = context.GetParcelTD 

//define Excel variables
Workbook workbook1 = Workbook.getWorkbook(new File("C:\\Users\\AKBAJPAI\\Downloads\\TD.xls")) 
def outputDataFileName = "C:\\Users\\AKBAJPAI\\Downloads\\Output.xls"
Workbook existingWorkbook = Workbook.getWorkbook(new File("C:\\Users\\AKBAJPAI\\Downloads\\TD.xls"));
WritableWorkbook workbookCopy = Workbook.createWorkbook(new File(outputDataFileName), existingWorkbook);
WritableSheet sheetToEdit = workbookCopy.getSheet(0);

//Index 0 will read the first sheet from the workbook, you can also specify the sheet name with "Sheet1"
Sheet sheet1 = workbook1.getSheet(0) 
WritableCell Events;

//To get the number of rows
size= sheet1.getRows().toInteger() 

//Iterate no of rows to get corresponding value
for(int i = 1;i<size;i++) {
     Cell v1 = sheet1.getCell(1,i)              //points to value1 and value2 from excel

     //set the values to properties test step and run the requests via groovy
     testRunner.testCase.getTestStepByName("Properties").setPropertyValue("ValueOne",v1.getContents())
    testRunner.testCase.getTestStepByName("GetParcel 1 - Request 1").run(testRunner, context)
    
    //get the values from response xml
    def Addholder = context?.expand('${GetParcel 1 - Request 1#response}')
    def Addresponse = new JsonSlurper().parseText(Addholder)
    def addvalue = Addresponse.ParcelState.Name
    def String event = addvalue.get(0).toString()
    log.info event
    //update the values in excel
     Label addL = new Label(2, i,event);
     Addcell = (WritableCell) addL;
     sheetToEdit.addCell(Addcell);
     }
     workbookCopy.write();
 workbook1.close();
 workbookCopy.close();
1

There are 1 best solutions below

0
Max Daroshchanka On

Option 1:

Check for null, or empty string

//get the values from response xml
def Addholder = context?.expand('${GetParcel 1 - Request 1#response}')
def Addresponse = Addholder ? new JsonSlurper().parseText(Addholder) : 'empty response'

Option 2:

Use try/catch:

//get the values from response xml
def Addholder = context?.expand('${GetParcel 1 - Request 1#response}')
def Addresponse
try {
    Addresponse = new JsonSlurper().parseText(Addholder)
} catch(IllegalArgumentException e) {
    Addresponse = 'empty response'
    // e.printStackTrace() or println(e.message) or use some logger
}