+ Start a Discussion
SalesforceAddictSalesforceAddict 

Test class for this apex class help?

public class fetchPicklistOptsController {    
    
  
    //Fetch Contact ID for Update Copntact and set default value contact have by default
    @AuraEnabled 
    public static Contact getContact(String contactId){                      
        Contact con = [SELECT Id,LastName,FirstName,MiddleName,Salutation,Title,AccountId,Classification_Target__c,Classification_Function__c,
                       CurrencyIsoCode,Source__c,Directory__c,Language__c,Chris_FormerStudent__c,Chris_Member__c,LeadSource,AssistantName,
                       AssistantPhone,Birthdate,Chris_PerDu__c,Chris_PersonallyMet__c,Chris_Private__c,Department,Email,E_Mail2__c,E_Mail3__c,Fax,GenerateTask__c,HomePhone,
                       MailingAddress,MailingCity,MailingCountry,MailingCountryCode,MandA_Participant__c,MandA_Program__c,MandA_Student__c,MissingName__c,MobilePhone,
                       OtherAddress,OtherCity,OtherCountryCode,OtherPhone,Parent_Account__c,OtherStreet,OtherState,MailingState,MailingStateCode,ReportsToId,website_user_id__c,
                       Twitter_Name__c,website_user__c,X_Hubspot_CompanyName__c,X_Hubspot_LinkedInBio__c,X_Hubspot_Source__c,X_Hupspot_Title__c FROM Contact where Id =:contactId];
        return con;       
    }
    
    @AuraEnabled
    public static List < String > getselectOptions(sObject objObject, string fld) {
        //system.debug('objObject --->' + objObject);
        //system.debug('fld --->' + fld);
        
        List < String > allOpts = new list < String > ();
        // Get the object type of the SObject.
        Schema.sObjectType objType = objObject.getSObjectType();
        
        // Describe the SObject using its object type.
        Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
        
        // Get a map of fields for the SObject
        map < String, Schema.SObjectField > fieldMap = objDescribe.fields.getMap();
        
        // Get the list of picklist values for this field.
        list < Schema.PicklistEntry > values =
            fieldMap.get(fld).getDescribe().getPickListValues();
        if(fld == 'MailingCountryCode' || fld == 'CurrencyIso'  || fld == 'OtherCountryCode' || fld == 'OtherCountryCode' || fld == 'MailingStateCode' || fld == 'OtherStateCode'){
            for (Schema.PicklistEntry a: values) {
                allOpts.add(a.getLabel());
            }
            
        }
        else{
            // Add these values to the selectoption list.
            for (Schema.PicklistEntry a: values) {
                allOpts.add(a.getValue());
            }
        }
        system.debug('allOpts ---->' + allOpts);
        allOpts.sort();
        return allOpts;
    }
    @AuraEnabled
    public static String fetchAllEmails(String email , String email2 , String email3){
      
        String str = '';
        for(Contact con: [SELECT Email,E_Mail2__c,E_Mail3__c FROM Contact]){
            if(con.email == email && (con.email != null || con.email != '') 
               || email == con.E_Mail2__c && (con.E_Mail2__c != null || con.E_Mail2__c != '')
               || email == con.E_Mail2__c && (con.E_Mail2__c != null || con.E_Mail2__c != '')
               || email == con.E_Mail3__c && (con.E_Mail3__c != null || con.E_Mail3__c != '')){
                   str = 'Email Already Exist!';
                   return str;
               }
        }
        return str;
    }
    
    @AuraEnabled
    public static String commitContact(Contact contactRecord, String updateInsertRecord){                   
        if(updateInsertRecord == 'Update'){
            try {                                  
                update contactRecord;
                return contactRecord.id;
                
            }
            catch(DmlException e) {
                return 'Error: ' + e.getMessage();
            }
        }
        if(updateInsertRecord == 'Insert'){
            try {            
                
                insert contactRecord;
                return contactRecord.id;
                
            }
            catch(DmlException e) {
                return 'Error: ' + e.getMessage();
            }
        }
        return null;
    }
    
    @AuraEnabled
    public static List < sObject > fetchLookUpValues(String searchKeyWord, String ObjectName) {
        system.debug('ObjectName-->' + ObjectName);
        String searchKey = searchKeyWord + '%';
        
        List < sObject > returnList = new List < sObject > ();
        
        // Create a Dynamic SOQL Query For Fetch Record List with LIMIT 5   
        String sQuery =  'select id, Name from ' +ObjectName + ' where Name LIKE: searchKey order by createdDate DESC limit 5';
        List < sObject > lstOfRecords = Database.query(sQuery);
        
        for (sObject obj: lstOfRecords) {
            returnList.add(obj);
        }
        return returnList;
    }
    
    @AuraEnabled 
    public static List<controllingFieldWrapper> getDependentMap(sObject objDetail, string contrfieldApiName,string depfieldApiName) {
        List<controllingFieldWrapper> MainDataControlling=new List<controllingFieldWrapper>();
        
        
        String controllingField = contrfieldApiName.toLowerCase();
        String dependentField = depfieldApiName.toLowerCase();
        
        Map<String,String> objResults = new Map<String,String>();
        
        Schema.sObjectType objType = objDetail.getSObjectType();
        if (objType==null){
            return MainDataControlling;
        }
        
        Map<String, Schema.SObjectField> objFieldMap = objType.getDescribe().fields.getMap();
        
        if (!objFieldMap.containsKey(controllingField) || !objFieldMap.containsKey(dependentField)){
            return MainDataControlling;     
        }
        
        Schema.SObjectField theField = objFieldMap.get(dependentField);
        Schema.SObjectField ctrlField = objFieldMap.get(controllingField);
        
        List<Schema.PicklistEntry> contrEntries = ctrlField.getDescribe().getPicklistValues();
        List<PicklistEntryWrapper> depEntries = wrapPicklistEntries(theField.getDescribe().getPicklistValues());
        List<String> controllingValues = new List<String>();
        
        Map<String,controllingFieldWrapper> ControllingFieldMap=new Map<String,controllingFieldWrapper>();
        
        for (Schema.PicklistEntry ple : contrEntries) {
            objResults.put(ple.getValue(), ple.getLabel());
            controllingValues.add(ple.getValue());
            
            controllingFieldWrapper ControllingFieldWrap=new controllingFieldWrapper();
            ControllingFieldWrap.fieldValue=ple.getValue();
            ControllingFieldWrap.fieldLabel=ple.getLabel();
            ControllingFieldWrap.DependentValues=new List<dependentFieldWrapper>();
            
            ControllingFieldMap.put(ple.getValue(), ControllingFieldWrap);
        }
        
        for (PicklistEntryWrapper plew : depEntries) {
            String validForBits = base64ToBits(plew.validFor);
            
            for (Integer i = 0; i < validForBits.length(); i++) {
                String bit = validForBits.mid(i, 1);
                if (bit == '1') {
                    if(ControllingFieldMap.containsKey(controllingValues.get(i))){
                        
                        dependentFieldWrapper fieldWrap=new dependentFieldWrapper();
                        fieldWrap.fieldLabel=plew.label;
                        fieldWrap.fieldValue=plew.value;
                        
                        ControllingFieldMap.get(controllingValues.get(i)).DependentValues.add(fieldWrap);
                    }
                }
            } 
        } 
        
        for(String Key:ControllingFieldMap.keySet()){
            MainDataControlling.add(ControllingFieldMap.get(Key));
        }
        return MainDataControlling;
    }
    
    public static String decimalToBinary(Integer val) {
        String bits = '';
        while (val > 0) {
            Integer remainder = Math.mod(val, 2);
            val = Integer.valueOf(Math.floor(val / 2));
            bits = String.valueOf(remainder) + bits;
        }
        return bits;
    }
    
    public static String base64ToBits(String validFor) {
        if (String.isEmpty(validFor)) return '';
        
        String validForBits = '';
        
        for (Integer i = 0; i < validFor.length(); i++) {
            String thisChar = validFor.mid(i, 1);
            Integer val = base64Chars.indexOf(thisChar);
            String bits = decimalToBinary(val).leftPad(6, '0');
            validForBits += bits;
        }
        
        return validForBits;
    }
    
    private static final String base64Chars = '' +
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
        'abcdefghijklmnopqrstuvwxyz' +
        '0123456789+/';
    
    
    private static List<PicklistEntryWrapper> wrapPicklistEntries(List<Schema.PicklistEntry> PLEs) {
        return (List<PicklistEntryWrapper>)
            JSON.deserialize(JSON.serialize(PLEs), List<PicklistEntryWrapper>.class);
    }
    
    public class PicklistEntryWrapper{
        public String active {get;set;}
        public String defaultValue {get;set;}
        public String label {get;set;}
        public String value {get;set;}
        public String validFor {get;set;}
        public PicklistEntryWrapper(){            
        }
        
    }
    
    Public Class controllingFieldWrapper{
        @auraEnabled
        Public String fieldValue{get;set;}
        @auraEnabled
        Public String fieldLabel{get;set;}
        @auraEnabled
        Public List<dependentFieldWrapper> DependentValues{get;set;}
    }
    
    Public Class dependentFieldWrapper{
        @auraEnabled
        Public String fieldValue{get;set;}
        @auraEnabled
        Public String fieldLabel{get;set;}
    }
    
}
Best Answer chosen by SalesforceAddict
Raj VakatiRaj Vakati
Try this code
 
@isTest
private class TestfetchPicklistOptsController {

   static testMethod void testCase1() {
	   
	    Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        
        
        insert uu;
		System.runAs(uu){
		Account testAccount = new Account();
		testAccount.Name='Test Account' ;
		insert testAccount;
		
		Contact cont = new Contact();
		cont.FirstName='Test';
		cont.LastName='Test';
		cont.E_Mail2__c='test@gmal.com',
		cont.E_Mail3__c='test@gmal.com',
		cont.email ='test@gmal.com',
		cont.Accountid= testAccount.id;
		insert cont;
		
		Contact cont1 = new Contact();
		cont1.FirstName='Test';
		cont1.LastName='Test';
		cont1.E_Mail2__c='test@gmal.com',
		cont1.E_Mail3__c='test@gmal.com',
		cont1.email ='test@gmal.com',
		cont1.Accountid= testAccount.id;
		
		
		
		fetchPicklistOptsController.getContact(cont.Id);
		fetchPicklistOptsController.getContact(cont.Id);
		fetchPicklistOptsController.getselectOptions('Contact','OtherStateCode');
				fetchPicklistOptsController.fetchAllEmails('test@gmal.com','test@gmal.com','test@gmal.com');

		fetchPicklistOptsController.commitContact(cont ,'Update');
		fetchPicklistOptsController.commitContact(cont1,'Insert');
		
		fetchPicklistOptsController.fetchLookUpValues('Test','Contact');
				fetchPicklistOptsController.getDependentMap('Contact','FistDepFields','FistDepFields');

		fetchPicklistOptsController.base64ToBits('asdasdasdasdasd');
		
		}
       
    }
}

 

All Answers

Raj VakatiRaj Vakati
Try this code
 
@isTest
private class TestfetchPicklistOptsController {

   static testMethod void testCase1() {
	   
	    Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        
        
        insert uu;
		System.runAs(uu){
		Account testAccount = new Account();
		testAccount.Name='Test Account' ;
		insert testAccount;
		
		Contact cont = new Contact();
		cont.FirstName='Test';
		cont.LastName='Test';
		cont.E_Mail2__c='test@gmal.com',
		cont.E_Mail3__c='test@gmal.com',
		cont.email ='test@gmal.com',
		cont.Accountid= testAccount.id;
		insert cont;
		
		Contact cont1 = new Contact();
		cont1.FirstName='Test';
		cont1.LastName='Test';
		cont1.E_Mail2__c='test@gmal.com',
		cont1.E_Mail3__c='test@gmal.com',
		cont1.email ='test@gmal.com',
		cont1.Accountid= testAccount.id;
		
		
		
		fetchPicklistOptsController.getContact(cont.Id);
		fetchPicklistOptsController.getContact(cont.Id);
		fetchPicklistOptsController.getselectOptions('Contact','OtherStateCode');
				fetchPicklistOptsController.fetchAllEmails('test@gmal.com','test@gmal.com','test@gmal.com');

		fetchPicklistOptsController.commitContact(cont ,'Update');
		fetchPicklistOptsController.commitContact(cont1,'Insert');
		
		fetchPicklistOptsController.fetchLookUpValues('Test','Contact');
				fetchPicklistOptsController.getDependentMap('Contact','FistDepFields','FistDepFields');

		fetchPicklistOptsController.base64ToBits('asdasdasdasdasd');
		
		}
       
    }
}

 
This was selected as the best answer
SalesforceAddictSalesforceAddict
its working fine but giving error in two method 
fetchPicklistOptsController.getselectOptions('Contact','OtherStateCode');
fetchPicklistOptsController.getDependentMap(''Contact','FistDepFields','FistDepFields'');
error is showing incorrect signature
 
SalesforceAddictSalesforceAddict
its working now i updated some values