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
SBNSBN 

Required field Missing exception in a Test class

Hi ,
I have a Apex Trigger which invokes a Apex class  on a Staging table and process the Lead JSON strings and Upserts the leads in Lead table and  links the lead to a Campaign.

This is My Apex class

public class IWS_Utility{

    public static void processLeadStage(List<Lead_Stage__c> lstLeadStage){
   
        Map<Id,Contact> mapExistingContacts = new Map<Id,Contact>();
        Map<String,IWS_Utility.contactDetails> mapContactsToProcess = new Map<String,IWS_Utility.contactDetails>();
        List<Contact_Roles__c> lstContactRoles = new List<Contact_Roles__c>();
        list<IWS_Utility.contactDetails> newContacts = new List<IWS_Utility.contactDetails>() ;  
        map< string, ID >  Campaignname2campaignid = new Map< string, ID >();
        List<CampaignMember> cmcheck = new List<CampaignMember>();
        Set<string> emailIds = new Set<string>() ;
        Set<datetime> messagetimestamp = new Set<datetime>() ;
        Set<string> nonMatchingEmails = new Set<string>() ;

       
        for ( Lead_Stage__c ImportRec : lstLeadStage )
        {
            if(!ImportRec.isProcessed__c){
                ImportRec.isProcessed__c= true;
                IWS_Utility.contactDetails e = IWS_Utility.parseContactFeedItem ( ImportRec.dataContent__c ) ;
                if (e!= NULL) {
                    newContacts.add(e) ;
                    mapContactsToProcess.put(e.emailAddress,e);
                    emailIds.add(e.emailAddress);
                   // messagetimestamp.add(ImportRec.messageTimestamp__c);
                }
            }
        }      
     
      list<CampaignMember> CMs = [
    SELECT id,CampaignId,Campaign.Name from CampaignMember] ;
       
        for ( CampaignMember cmitem : CMs ) {    
          
         
      Campaignname2campaignid.put(cmitem.Campaign.Name,cmitem.Campaignid);   
    
      }
       id Campid =  Campaignname2campaignid.get('Lead Gen Campaign') ;
       system.debug('the camp id is'+ Campid );
       
        List<Contact> lstContacts = [Select Id,AccountId,Email,FirstName,LastName,Phone,(Select Id from Contact_Roles__r where Contact_Role__c = 'Individual Insurance Lead'),(Select Id from CampaignMembers) from Contact where Email In:emailIds limit 1000];
        List<Contact> lstContacts2Update = new List<Contact>();
       
        for(Contact c: lstContacts)
        {
            if(emailIds.contains(c.Email)){
                System.debug('contact exists');
                if(c.FirstName==null || c.Phone==null)
                {
                    if(c.FirstName==null)
                        c.FirstName = mapContactsToProcess.get(c.Email).firstName;
                    if(c.Phone == null)
                        c.Phone = mapContactsToProcess.get(c.Email).phoneNumber;
                    if(c.MailingPostalCode  == null)
                        c.MailingPostalCode = mapContactsToProcess.get(c.Email).zipCode;       
                    lstContacts2Update.add(c); 
                }
                if(c.Contact_Roles__r.size()==0)               
                {
                    lstContactRoles.add(new Contact_Roles__c(Contact__c=c.Id,Account__c=c.Accountid,Contact_Role__c = 'Individual Insurance Lead'));
                }
                if(c.CampaignMembers.size()==0)
                    cmcheck.add(new CampaignMember(ContactId=c.Id,CampaignId =Campid,Status='Responded'));
                    emailIds.remove(c.Email);
            }
        }
       
        List<Lead> lstUpdateLeads = new List<Lead>();       
           
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.assignmentRuleHeader.useDefaultRule= true;
       
        for(Lead  l : [Select Id,Email,FirstName,LastName,Phone,(Select Id from CampaignMembers where CampaignId =:Campid ) from Lead where Email In:emailIds]){
            
            if(emailIds.contains(l.Email))
            {
                l.FirstName = mapContactsToProcess.get(l.Email).firstName;
                l.LastName = mapContactsToProcess.get(l.Email).lastName;
                l.Phone = mapContactsToProcess.get(l.Email).phoneNumber;
                l.company =l.FirstName+''+l.LastName ;
                l.postalcode = mapContactsToProcess.get(l.Email).zipCode;
                l.setOptions(dmo);
                lstUpdateLeads.add(l);
                if(l.CampaignMembers.size()==0)
                {
                    cmcheck.add(new CampaignMember(LeadId=l.Id,CampaignId =Campid,Status='Responded'));
                }
                emailIds.remove(l.Email);
            }
        }
       
        List<Lead> lstNewLeads = new List<Lead>();       
      
       
        for(String emailId: emailIds)
        {
            IWS_Utility.contactDetails feedCon = mapContactsToProcess.get(emailId);
            lstNewLeads.add(new Lead(EMail=emailId,Firstname=feedCon.firstName,Phone=feedCon.phoneNumber,postalcode=feedCon.zipCode,LastName=feedCon.LastName,company=feedCon.firstName+' '+feedCon.LastName,LeadSource ='Web'));
        }
       
         for(lead l : lstNewLeads)
           l.setOptions(dmo);
       
        if(lstContacts2Update.size()>0)
            update lstContacts2Update;

        if(lstContactRoles.size()>0)
            insert lstContactRoles;

        if(lstUpdateLeads.size()>0)
            update lstUpdateLeads;
           
        if(lstNewLeads.size()>0){
            insert lstNewLeads;
             system.debug('the camp id is 1'+ Campid );
            for(lead l : lstNewLeads)
                cmcheck.add(new CampaignMember(LeadId=l.Id,CampaignId =Campid,Status='Responded'));
            }
             system.debug(' size is '+ cmcheck.size());
        if(cmcheck.size()>0)
            insert cmcheck;    
    }

    public static contactDetails parseContactFeedItem ( string jsonEnrollmentString ) {
       
        JSONParser parser = JSON.createParser(jsonEnrollmentString);
        contactDetails sr ;

        while (parser.nextToken() != null)
        {
            sr = (contactDetails)parser.readValueAs(contactDetails.class);
        }
        return(sr) ;
    }
   

    public class contactDetails {
       
        public string lastName      {get; set;}
        public string firstName     {get; set;}
        public string emailAddress  {get{return emailAddress.toLowerCase();} set;}
        public string phoneNumber   {get; set;}
        public string zipCode       {get; set;}
    }
   

   

and My Test Class is

@isTest
private class web2lead_test {
    static testMethod void web2lead() {      
    
  Campaign testCampaign;  

   testCampaign = new Campaign(name = 'Lead Gen Campaign');            
  
     Lead a1 = new Lead (
      LastName = 'test1',
      Phone ='1234567890',
      Email = ‘testing@gmail.com’) ;
     insert a1 ;       

   
    Lead L = new Lead (
      FirstName = 'Lead',
      LastName = 'test',
      Company = 'abcde',      
      email = 'testing3@gmail.com' ) ;
     insert L ;
   
     Lead L1 = new Lead (
      FirstName = 'Lead',
      LastName = 'test',
      Company = 'abcd',      
      email = 'testing4@gmail.com' ) ;
     insert L1 ;     
    
  
    CampaignMemberStatus status1 = new CampaignMemberStatus(
        CampaignID = testCampaign.id ,
        Label = 'Responded',
        SortOrder = 2);     
   insert status1 ;  

List<Lead_Stage__c> Leadstagerecord = new List<Lead_Stage__c>() ;
  
    Lead_Stage__c importRecord = new Lead_Stage__c(dataContent__c = '{"firstName":"Teddy","lastName":"Roosevelt","emailAddress":"ro@os.ev","phoneNumber":"","zipCode":"11215"}');
   
    
    Leadstagerecord.add(importRecord) ;
  
   /* Lead_Stage__c importRecord1 = new Lead_Stage__c(dataContent__c = '{"firstName":"Teddy","lastName":"Roosevelt","emailAddress":"ro@os.ev","phoneNumber":"","zipCode":"11215"}');
  
    
    Leadstagerecord.add(importRecord1) ;
 
     Lead_Stage__c importRecord2 = new Lead_Stage__c(dataContent__c = '{"firstName":"Teddy","lastName":"Roosevelt","emailAddress":"testing2@gmail.com","phoneNumber":"1234567890","zipCode":"11215"}');
  
    
     Leadstagerecord.add(importRecord2) ;
 
     Lead_Stage__c importRecord3 = new Lead_Stage__c(dataContent__c = '{"firstName":"Teddy","lastName":"Roosevelt","emailAddress":"testing4@gmail.com","phoneNumber":"","zipCode":"11215"}');
  
    
      Leadstagerecord.add(importRecord3) ;

   Test.startTest();
    insert Leadstagerecord ;
  
    Test.stopTest();

If I run the above test Its throwing an error :

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, IWS_Code.processleadFeedItems: execution of BeforeInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Attempted to add a campaign member where either the member id '00Qi000000Gtb1T' or the campaign id 'null' is null.: []

Class.IWS_Code.IWS_Utility.processLeadStage: line 122, column 1


Can Anyone help me out on this?

Thanks
Sri549Sri549
Hello SBN,
The Issue which you have got Required field Missing exception in a Test class which says like in test class when your inserting with some values of different objects. you are not so inserting or missing  some fields to include in any of object please see whether all required fields in different objects are considered or not.so that you can resolve that kind of error in test class.

if you still get same error please reply me saying or else if your error have solved

Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.

Thank You,
Srinivas
SFDC Certified Developer