function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pedro Garcia GPedro Garcia G 

testing @AuraEnabled apex method

How could I make the unit test for an @AuraEnabled apex method?

The Aura component has a lightning:datatable component which load a custom data (it's not a sObject) from a CSV file.

The app allows select a row and send it to the apex insertContact method. This method parse the csv row to a Contact object through a mapping and save the record.

The method works very well, now I'm trying to make the Unit Test but It fails. The lightining controller sends a  Map<Object,Object> (see the code) but when I try to simulate this in the Unit Test it's sending a Map<String,Object>.

What is the best way to make the Unit Test for this scenario? Thanks!!!

I need to make the Unit Test to deploy it on production.
 
public static List<Contact> insertContact(List<Object> selectedItems){
        
                
        List<Contact> contactList = new List<Contact>();
        
        Map<Object, Object> fieldMap =  (Map<Object, Object>) selectedItems[0];

        Set<Object> fieldSet = new Set<Object>();
        
        fieldSet =  fieldMap.keySet();
        
        Map<String,String> fieldsMapping = CASContact.fieldsMapping;
        
        for(Integer i=0; i< selectedItems.size(); i++){
            
            Map<Object, Object> mObject =  (Map<Object, Object>) selectedItems[i];
            
            Contact newContact = new Contact();
            
            for(Object fieldname : fieldSet){
                
                if(fieldsMapping.get((String) fieldname) !=null)
                newContact.put(fieldsMapping.get((String) fieldname), mObject.get((String) fieldname).toString());
                
            }
            
            contactList.add(newContact);
           
        }
        
        System.debug('cas7.13>>>'+contactList);
        
        Database.SaveResult[] srList = Database.insert(contactList, false);
        
        // Iterate through each returned result
        for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                System.debug('cas>>Successfully inserted account. Account ID: ' + sr.getId());
            }
            else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('cas>>The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('cas>>Account fields that affected this error: ' + err.getFields());
                }
            }
        }
        
        return contactList;
        
    }

my Unit Test
@isTest static void insertContactTestTrue(){



        String selectedItems = '[{"cas_id":"6050902094","last_name":"pepe","first_name":"papo","permanent_street_address":"Ap #273-2abc565 Est Street","permanent_city":"Belxfast","permanent_state":"ursula","permanent_postal_code":"12345","permanent_country_name":"Papua New Guinea","Phone":"","Mobile":"","email":"a@nadiesabe.edu","program_id_0":"8425651082805990996","program_id_1":"","local_status_0":"Rejected - GPA","local_status_1":"Interview Scheduled","application_status_0":"Received"},{"cas_id":"8551822992","last_name":"papo","first_name":"pupa","permanent_street_address":"9623 Dondequiera. Rd.","permanent_city":"Germersheim","permanent_state":"RP","permanent_postal_code":"5819","permanent_country_name":"Uganda","Phone":"","Mobile":"","email":"ac.mattis.semper@esttempor.ca","program_id_0":"8425651082805990996","program_id_1":"","local_status_0":"Deferred","local_status_1":"","application_status_0":"Verified"}]';

        List<Object> fieldList = (List<Object>)JSON.deserializeUntyped(selectedItems);

        List<Contact> contacts = CASContact.insertContact(fieldList);

        System.assertEquals(2, contacts.size());

    }

 
Maharajan CMaharajan C
Hi Pedro,

I think there is some problem in your class.

See if your test data is correct then there is some Map conversion system exception is coming from the Apex Class while i am running.

So i have tweaked your class like below and its working fine got 95 % coverage for this method.

Public class CASContact
{
public static List<Contact> insertContact(List<Object> selectedItems){

Map<String,String> fieldsMapping = new Map<String,String>();   // Comment These lines while you copy this method
fieldsMapping.put('last_name', 'LastName');                                  // Comment These lines while you copy this method
fieldsMapping.put('first_name', 'FirstName');                                  // Comment These lines while you copy this method
fieldsMapping.put('email', 'Email');                                                  // Comment These lines while you copy this method

List<Contact> contactList = new List<Contact>();
Map<String, Object> fieldMap = (Map<String, Object>) selectedItems[0];
Set<String> fieldSet = new Set<String>();
fieldSet = fieldMap.keySet();

//  Map<String,String> fieldsMapping = CASContact.fieldsMapping;                   // Please Uncomment this line while you copy this method

for(Integer i=0; i< selectedItems.size(); i++){

Map<String, Object> mObject = (Map<String, Object>) selectedItems[i];

Contact newContact = new Contact();

for(String fieldname : fieldSet){

if(fieldsMapping.get((String) fieldname) !=null)
newContact.put(fieldsMapping.get((String) fieldname), mObject.get((String) fieldname));

}
contactList.add(newContact);
}

System.debug('cas7.13>>>'+contactList);

Database.SaveResult[] srList = Database.insert(contactList, false);

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('cas>>Successfully inserted account. Account ID: ' + sr.getId());
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('cas>>The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('cas>>Account fields that affected this error: ' + err.getFields());
}
}
}

return contactList;
}   // Method End

}


Thanks,
Maharajan.C
Pedro Garcia GPedro Garcia G
Hi Maharajan,

Thanks for you reply... it's still have an error on the line: Map<String, Object> fieldMap = (Map<String, Object>) selectedItems[0];

System.TypeException: Invalid conversion from runtime type CASContactTest.ndclass to Map<String,ANY>

The class works very well in the real environment but I've able to create the proper Unit Test... The ContactTest create the Map
String selectedItems = '[{"cas_id":"6050902094","last_name":"pepe","first_name":"papo","permanent_street_address":"Ap #273-2abc565 Est Street","permanent_city":"Belxfast","permanent_state":"ursula","permanent_postal_code":"12345","permanent_country_name":"Papua New Guinea","Phone":"","Mobile":"","email":"a@nadiesabe.edu","program_id_0":"8425651082805990996","program_id_1":"","local_status_0":"Rejected - GPA","local_status_1":"Interview Scheduled","application_status_0":"Received"},{"cas_id":"8551822992","last_name":"papo","first_name":"pupa","permanent_street_address":"9623 Dondequiera. Rd.","permanent_city":"Germersheim","permanent_state":"RP","permanent_postal_code":"5819","permanent_country_name":"Uganda","Phone":"","Mobile":"","email":"ac.mattis.semper@esttempor.ca","program_id_0":"8425651082805990996","program_id_1":"","local_status_0":"Deferred","local_status_1":"","application_status_0":"Verified"}]';

        List<Object> fieldList = (List<Object>)JSON.deserializeUntyped(selectedItems);

        List<Contact> contacts = CASContact.insertContact(fieldList);

It's a Map<String, ANY>... the class is expecting Map<Object,Object>... is there another way to make the unit test of @AuraEnabled??

thanks