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
NK ShaNK Sha 

Test class : Execution gets failed

global class LtngImportProcessController {
   
    @AuraEnabled
    public static void ReadCSVFile(String base64Data) {
       try {
           base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
          Blob blobFile = EncodingUtil.base64Decode(base64Data);
           String stringCSVFile = blobFile.toString();                       
           System.debug('##After Blob to String##'+' '+stringCSVFile);
           String[] stringCSVRecords = stringCSVFile.split('\n');
           System.debug('@@After Split@@'+' '+stringCSVRecords);
           set<String>  objectNameSet = new set<String>();
          
           for(Integer i=1;i<stringCSVRecords.size();i++){
              string[] splitRecords = stringCSVRecords[i].split(',');
              objectNameSet.add(splitRecords[0]);
           }
           MetadataService.MetadataPort service = createService();        
           List<MetadataService.Metadata> customObjList = new List<MetadataService.Metadata>();  
           for(String objName : objectNameSet){
              MetadataService.CustomObject  customobject = new MetadataService.CustomObject();
              System.debug('$$$$$$$$$$$$$$$');
           customobject.fullName    = objName+'__c';
                 customobject.label       = objName;
                 customobject.pluralLabel = objName+'s';
                 customObject.nameField = new MetadataService.CustomField();
                 customobject.nameField.type_x = 'Text';
                 customobject.nameField.label  = 'Custom created field';
                 customobject.deploymentStatus = 'Deployed';
                 customObject.sharingModel     = 'ReadWrite';
                 customObjList.add(customobject);
            }  
           List<MetadataService.SaveResult> objectCreatedResult = service.createMetadata(customObjList);
                List<MetadataService.Metadata> customfieldList = new List<MetadataService.Metadata>();
                for(integer i=1;i<stringCSVRecords.size();i++) {
                    String[] splitRecord =  stringCSVRecords[i].split(',');//size of return list or array is 20
                    MetadataService.CustomField customField = new MetadataService.CustomField();
                        customField.fullName = splitRecord[0]+'__c.'+splitRecord[1]+'__c';
                        customField.label    = splitRecord[1];
                        customField.type_x   = splitRecord[2];
                      if(splitRecord[2] == 'Lookup'){
                         System.debug('INSIDE LOOKUP CREATION');
                          customField.relationshipLabel = 'Tests';
                          customField.relationshipName  = 'Tests';
                          customField.referenceTo       = splitRecord[3];
                      }
                       
                      if(splitRecord[2] == 'Picklist'){
                          System.debug('INSIDE PICKLIST CREATION');
                            string[] dropdownList = splitRecord[7].split(';');
                            System.debug('The DropDownList'+' '+dropdownList);
                            Metadataservice.Picklist ptObj = new Metadataservice.Picklist();  
                            ptObj.sorted= Boolean.valueOf(splitRecord[10].trim());
                            List<MetadataService.PicklistValue>  addValueList = new List<metadataService.PicklistValue>();
                            for(String dropdownValue : dropdownList){
                               metadataservice.PicklistValue valueObj = new metadataservice.PicklistValue();
                                System.debug('The Name Picklist Value'+' '+dropdownValue);
                                valueObj.fullName  = dropdownValue;
                                valueObj.default_x = Boolean.valueOf(splitRecord[11].trim());
                                addValueList.add(valueObj);
                            }
                            ptObj.picklistValues = addValueList;
                            customField.picklist = ptObj ;
                       }
                      customfieldList.add(customField);
                }

        List<MetadataService.Metadata> addProfileList = new List<MetadataService.Metadata>();
      
        MetadataService.Profile admin = new MetadataService.Profile();
        admin.fullName = 'Admin';
        admin.custom = false;
        List<MetadataService.ProfileFieldLevelSecurity> addFieldsList = new List<MetadataService.ProfileFieldLevelSecurity>();
        for(Integer i=1;i<stringCSVRecords.size();i++){
            string[] splitRecord = stringCSVRecords[i].split(',');
            MetadataService.ProfileFieldLevelSecurity fieldSec = new MetadataService.ProfileFieldLevelSecurity();
            fieldSec.field=splitRecord[0]+'__c.'+splitRecord[1]+'__c';
            fieldSec.editable=true;
            addFieldsList.add(fieldSec);
        }
           admin.fieldPermissions  = addFieldsList;
           addProfileList.add(admin);
           List<MetadataService.SaveResult> profileAssignResults = service.updateMetadata(addProfileList);   
            Integer j=1;
           set<String> DupObjNameSet = new set<String>();         
           for(Integer i=1;i<stringCSVRecords.size();i++){
              string[] splitRecords = stringCSVRecords[i].split(',');
              DupObjNameSet.add(splitRecords[0]);
           }
            
            MetadataService.Layout layout = new MetadataService.Layout();
           for(String DupObj : DupObjNameSet){
                layout =  
                   (MetadataService.Layout) service.readMetadata('Layout',new String[] { DupObj+'__c'+'-'+DupObj+' '+'Layout' }).getRecords()[0];
                List<MetadataService.LayoutItem> ColItemList1 =  layout.LayoutSections[0].LayoutColumns[0].layoutItems;
                List<MetadataService.LayoutItem> ColItemList2 =  layout.LayoutSections[0].LayoutColumns[1].layoutItems;
                /*Step-3 Inner Loop/Child Loop For --Custom Fields are going to add in every Object LayoutItemList i.e lItemList*/
                for(Integer i=j;i<stringCSVRecords.size();i++){
                    string[] splitRecord = stringCSVRecords[i].split(',');
                    /* Below Condition Help to create layout for different Objects */
                    if(DupObj == splitRecord[0] && splitRecord[20].contains('TRUE')){
                        System.debug('I M TRUE I M TRUE I M TRUE I M TRUE');  
                         MetadataService.LayoutItem FieldItem = new MetadataService.LayoutItem();
                          if(math.mod(i, 2) == 0){
                            FieldItem.Field = splitRecord[1]+'__c';
                            ColItemList1.add(FieldItem);
                        }else{
                           FieldItem.Field = splitRecord[1]+'__c';
                           ColItemList2.add(FieldItem);
                        }
                     }else if(DupObj != splitRecord[0]){
                        j = i;
                        break;
                      }
                }
   
          List<MetadataService.SaveResult> results =service.updateMetadata(new List<MetadataService.Layout>{layout});      // FIELD ADDED TO LAYOUT
         }
       
          
     }
        catch (Exception e){
            System.debug('Exception Found'+' '+e);
            AuraHandledException ahe = new AuraHandledException(e.getMessage());
            ahe.setMessage(e.getMessage());
            throw ahe;
        }
    }
    @AuraEnabled
    public static MetadataService.MetadataPort createService() {
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        
        System.debug('The Session Id is now '+' '+Utils.getSessionIdFromVFPage(Page.SessionIdVF));
        //service.SessionHeader.sessionId = sessionId();
        service.SessionHeader.sessionId = Utils.getSessionIdFromVFPage(Page.SessionIdVF);
        return service;
    }       
 
}
NK ShaNK Sha
User-added image

I am facing this type of error : 

can any one help me on that

This is my test class

@isTest
public class LtngImportProcessControllerTest{
    static String str = 'Name,AccountNumber,Type,Accountsource,Industry\n Esha Patharabe,10001,Prospect,Test,Banking\n Trupti Nimje,10002,Prospect,Test,Banking';       

    public static String[] csvFileLines;
    public static Blob csvFileBody;
    public static string[] CSVRecords;     
    static testMethod void testAllMethods(){
        
        contact objContact =  new Contact(lastName='test contact');
        insert objContact ;
        
        //String csvBody = EncodingUtil.base64Encode(csvBlob);
        blob file=  Blob.valueOf('sample text');
        String csvBody = EncodingUtil.base64Encode(file);
        Attachment objAttachment=new Attachment();
        objAttachment.Body= file;
        objAttachment.ContentType = 'text/plain; charset=UTF-8';
        objAttachment.Name = 'test Attachment';
        objAttachment.ParentId = objContact.Id;
        insert objAttachment;
        
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n');

        //LtngImportProcessController importData = new LtngImportProcessController ();
        //importData.ReadCSVFile= ReadCSVFile;
        LtngImportProcessController.ReadCSVFile(file.toString());
        Test.stopTest();
    }
    static testmethod void testfileuploadNegative(){
    
        contact objContact =  new Contact(lastName='test contact');
        insert objContact ;
        
        blob file=  Blob.valueOf('sample text');
        Attachment objAttachment=new Attachment();
        objAttachment.Body= file;
        objAttachment.ContentType = 'text/plain; charset=UTF-8';
        objAttachment.Name = 'test Attachment';
        objAttachment.ParentId = objContact.Id;
        insert objAttachment;
        
        
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n');

        //LtngImportProcessController importData = new LtngImportProcessController();
        //importData.importCSVFile();
        LtngImportProcessController.ReadCSVFile(file.toString());
        Test.stopTest();
    }
}