Run time error- java.lang.ClassCastException: class java.util.Collections$SingletonList cannot be cast to class java.util.Iterator

430 views
Skip to first unread message

Prerana Sharma

unread,
Sep 27, 2023, 8:02:53 AM9/27/23
to REST assured
Hi There,

I am trying to run the same test with multiple data that is being fetched from the excel sheet. Therefore, I had to use Collections.singletonList to pass the payload to my test using data provider iterator. 
Now, I am able to build my payload and get the data appropriately. But, when I try to pass the payload to the test then it shows run time error. The error, data provider class and the test is as following. Can some one advice on what needs to be achieved or help fix the error. Thanks in advance.

Error 
java.lang.RuntimeException: java.lang.ClassCastException: class java.util.Collections$SingletonList cannot be cast to class java.util.Iterator (java.util.Collections$SingletonList and java.util.Iterator are in module java.base of loader 'bootstrap')

at org.testng.internal.invokers.MethodInvocationHelper.invokeMethodNoCheckedException(MethodInvocationHelper.java:57)
at org.testng.internal.invokers.MethodInvocationHelper.invokeDataProvider(MethodInvocationHelper.java:157)
at org.testng.internal.Parameters.handleParameters(Parameters.java:803)
at org.testng.internal.Parameters.handleParameters(Parameters.java:728)
at org.testng.internal.invokers.ParameterHandler.handleParameters(ParameterHandler.java:72)
at org.testng.internal.invokers.ParameterHandler.createParameters(ParameterHandler.java:51)
at org.testng.internal.invokers.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:924)
at org.testng.internal.invokers.TestInvoker.invokeTestMethods(TestInvoker.java:194)
at org.testng.internal.invokers.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:148)
at org.testng.internal.invokers.TestMethodWorker.run(TestMethodWorker.java:128)



data provider class

package org.example.ContactAddPOJO;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.example.ExcelUtils;
import org.testng.annotations.DataProvider;

import java.io.IOException;
import java.util.*;

public class Cur_CreateNestedJSONFromPOJOClasses {

    @DataProvider(name="TestAdd")
    public static <jsonArray> Iterator<Object[]> setPayload () throws IOException, InvalidFormatException {
   
        List<String> nestedJsonPayload = new ArrayList<>();
   
        List<LinkedHashMap<String, String>> requiredExcelData = ExcelUtils.getExcelDataAsListOfMap("Book2", "Sheet1");

        for (LinkedHashMap<String, String> data : requiredExcelData) {

            Cur_NestedPOJO nestedPOJO = new Cur_NestedPOJO();

            nestedPOJO.customer.put("Email", data.get("Email"));
            nestedPOJO.customer.put("FirstName", data.get("FirstName"));
            nestedPOJO.customer.put("LastName", data.get("LastName"));

            List addressesArray = new ArrayList<>();

            Cur_Addresses billToAddress = new Cur_Addresses();
            billToAddress.street_details.add(data.get("BillingStreet"));
            billToAddress.setCity(data.get("BillingCity"));
            billToAddress.setRegion_id(Integer.parseInt(data.get("Billing_region_id")));
            billToAddress.setCountry_id(data.get("BillingCountry"));
            billToAddress.setPostcode(data.get("BillingPostalCode"));
            billToAddress.setTelephone(data.get("Phone"));

            Cur_Custom_attributes addressDetails_custom_attributes = new Cur_Custom_attributes();
            addressDetails_custom_attributes.setAttribute_code("target_address_id");
            addressDetails_custom_attributes.setValue(data.get("CNo"));

            Cur_Addresses shipToAddress = new Cur_Addresses();
            shipToAddress.street_details.add(data.get("ShippingStreet"));
            shipToAddress.setCity(data.get("ShippingCity"));
            shipToAddress.setRegion_id(Integer.parseInt(data.get("Billing_region_id")));
            shipToAddress.setCountry_id(data.get("ShippingCountry"));
            shipToAddress.setPostcode(data.get("ShippingPostalCode"));
            shipToAddress.setTelephone(data.get("Phone"));
     

            addressesArray.add(billToAddress);
            billToAddress.custom_attributes.add(addressDetails_custom_attributes);
            addressesArray.add(shipToAddress);
            shipToAddress.custom_attributes.add(addressDetails_custom_attributes);


            nestedPOJO.customer.put("addresses", addressesArray);

            Cur_Extension_attributes extensionAttributes = new Cur_Extension_attributes();
            extensionAttributes.setIs_subscribed(false);
            Cur_Extension_attributes_details extensionAttributesDetails = new Cur_Extension_attributes_details();
            extensionAttributesDetails.setStatus(1);
            extensionAttributes.setCompany_attributes(extensionAttributesDetails);


            nestedPOJO.customer.put("extension_attributes", extensionAttributes);

            List my_custom_attributes = new ArrayList();

            Cur_Custom_attributes custom_attributes1 = new Cur_Custom_attributes();
            custom_attributes1.setAttribute_code("target_customer_id");
            Cur_Custom_attributes custom_attributes2 = new Cur_Custom_attributes();
            custom_attributes4.setAttribute_code("target_salesperson_id");
            custom_attributes4.setValue(data.get("SalespersonCode"));
            Cur_Custom_attributes custom_attributes3 = new Cur_Custom_attributes();
            custom_attributes5.setAttribute_code("is_salesperson");
            custom_attributes5.setValue("0");
         

            my_custom_attributes.add(custom_attributes1);
            my_custom_attributes.add(custom_attributes2);
            my_custom_attributes.add(custom_attributes3);

            nestedPOJO.customer.put("custom_attributes", my_custom_attributes);

            ObjectMapper objectMapper = new ObjectMapper();
            nestedJsonPayload = Collections.singletonList(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(nestedPOJO));
            //System.out.println(nestedJsonPayload);

        }

        return (Iterator<Object[]>) nestedJsonPayload;
    }
}



Test

public class CreateContact {
    public static Response CreateContactResponse;


    @Test(dataProvider = "TestAdd", dataProviderClass = Cur_CreateNestedJSONFromPOJOClasses.class)
    public void CreateContact(String nestedJsonPayload) {
        try{
            CreateContactResponse = RestAssured
                    .given()
                    .contentType("application/json")
                    .log()
                    .all()
                    .header("Authorization", "Bearer " + Token)
                    .body(nestedJsonPayload)
                    .post(CreateContactURI)
                    .then()
                    .statusCode(200)
                    .log()
                    .all()
                    .extract()
                    .response();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

Michael Pinnegar

unread,
Sep 27, 2023, 8:21:55 AM9/27/23
to rest-a...@googlegroups.com
Your cast is failing.

return (Iterator<Object[]>) nestedJsonPayload

Why are you casting this object? Java util collections can give you iterators just call .iterator() on nestedJsonPaylod.

--
You received this message because you are subscribed to the Google Groups "REST assured" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rest-assured...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rest-assured/cfefefd4-3d54-44f3-a583-0131f4ca42f4n%40googlegroups.com.

Prerana Sharma

unread,
Oct 3, 2023, 12:19:37 PM10/3/23
to REST assured
Thanks for responding Jaz. 

I had tried doing that earlier. The code then sends only the last iteration data to the test. other iterations do not execute, but only the last one is sent and executed. 

Prerana Sharma

unread,
Oct 3, 2023, 12:25:07 PM10/3/23
to REST assured
This is what I changed in my dataprovider class

data provider class

package org.example.ContactAddPOJO;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.example.ExcelUtils;
import org.testng.annotations.DataProvider;

import java.io.IOException;
import java.util.*;

public class Cur_CreateNestedJSONFromPOJOClasses {

    @DataProvider(name="TestAdd")
    public static <jsonArray> Iterator<String> setPayload () throws IOException, InvalidFormatException {
        return nestedJsonPayload.iterator();
    }
}

Prerana Sharma

unread,
Nov 7, 2023, 9:39:58 AM11/7/23
to REST assured
Hi Jaz,

I just wanted to update and thank you for recommending the change. I was able to achieve what was needed a few hours later to my last response on this chain. Your advise is much appreciated. 

On Wednesday, September 27, 2023 at 5:51:55 PM UTC+5:30 jaz...@gmail.com wrote:

Michael Pinnegar

unread,
Nov 7, 2023, 9:46:18 AM11/7/23
to rest-a...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages