-2

Can anyone helps me out in writing the test class for below apex class.

I know that I should not post it here asking for this kind of questions but as I am new to apex and I need to deploy so I was asking.

Any help will be appreciated here.

My apex class is below.

public class LeadTriggerHandler {

Static List<Lead> noParentLeadList = new List<Lead>();
Static List<Lead> parentLeadList = new List<Lead>();
Static List<Contact> insertConList = new List<Contact>();
Static List<Contact> insertConList1 = new List<Contact>();

public static void afterInsertProcess(List<Lead> leadList){

    List<hed__Relationship__c> insertRelationShipList = new List<hed__Relationship__c>();
    List<hed__Affiliation__c> insertaffiliationList = new List<hed__Affiliation__c>();
    List<hed__Affiliation__c> insertaffiliationList1 = new List<hed__Affiliation__c>();


    for(Lead leadKey : leadList){
        if(leadKey.Parent_or_guardian__c == false){
            //list which contains Parent__c = false
            noParentLeadList.add(leadKey);
        }
        else{
            //list which contains Parent__c = true
           parentLeadList.add(leadKey);
        }
    }
   //Creates affiliation records if form has only student details
    if(noParentLeadList != null && noParentLeadList.size() > 0){
        Map<Id,List<Contact>> insertConMap1 = createContactNoParent(noParentLeadList);
        Map<Id,String> LeadPrimaryProgram = new Map<Id,String>();
        set<Id> Possiblelead = new set<Id>();
        for(lead idkey :noParentLeadList){
            Possiblelead.add(idKey.Id);
        }

        //Map<Id,list<String>> secondaryPrimaryProgram = new Map<Id,list<String>>();
        for (Lead lead:[select Id,What_is_your_primary_program_of_interest__c from Lead where Id in :Possiblelead]){
            LeadPrimaryProgram.put(lead.id,lead.What_is_your_primary_program_of_interest__c);

        for(Id idKey : insertConMap1.keySet()){
            insertConList1.addAll(insertConMap1.get(idKey));
        }
        insert insertConList1;


        //Build Map of Accounts per Primary Program
        Map<String,Id> accNamesToIdsMap2 = new Map<String,Id>();
        for(Account acc : [select id,Name,SIS_Prog_Code__c from account where Name in : LeadPrimaryProgram.values() AND RecordType.DeveloperName = 'Academic_Program' and SIS_Prog_Code__c=null]){
            accNamesToIdsMap2.put(acc.Name,acc.Id);
        }

        for(Id IdKey : insertConMap1.keySet()){

            //creates affiliation record for primary program
            if (LeadPrimaryProgram.containsKey(idKey)){

                string PrimaryProgram=LeadPrimaryProgram.get(idKey);
                if (accNamesToIdsMap2.containsKey(PrimaryProgram)){          
                    Id AccountId=accNamesToIdsMap2.get(PrimaryProgram);
                        insertaffiliationList1.add(new hed__Affiliation__c(hed__Account__c= AccountId,
                                                            hed__Contact__c=insertConMap1.get(IdKey).get(0).Id,
                                                            hed__Primary__c = true,
                                                            hed__Role__c='Prospect'));
                }
            }

        }
        insert insertaffiliationList1;
        ConvertLeads1(insertConMap1);
    }
    //Creates relationship and affiliation records if form is filled by parent
    if(parentLeadList != null && parentLeadList.size() > 0){
        Map<Id,List<Contact>> insertConMap = createContactParent(parentLeadList);
        Map<Id,String> LeadPrimaryProgram1 = new Map<Id,String>();
        set<Id> Possiblelead1 = new set<Id>();
        for(lead idkey :parentLeadList){
            Possiblelead1.add(idKey.Id);
        }
        for (Lead lead1:[select Id,What_is_your_primary_program_of_interest__c from Lead where Id in :Possiblelead1]){
            LeadPrimaryProgram1.put(lead1.id,lead1.What_is_your_primary_program_of_interest__c);
        }
        //contact insert operation
        for(Id idk : insertConMap.keySet()){
            insertConList.addAll(insertConMap.get(idk));
        }
        insert insertConList;

        //setting up inserted contact's Id in RelationShip__c object.
        for(Id IdKey : insertConMap.keySet()){
            hed__Relationship__c rel = new hed__Relationship__c(
                hed__Contact__c = insertConMap.get(IdKey).get(0).Id,
                hed__RelatedContact__c = insertConMap.get(IdKey).get(1).Id,
                hed__Type__c = 'Parent'
            );
            insertRelationShipList.add(rel);
            //Creates affiliation record for primary program


                Map<String,Id> accNamesToIdsMap1 = new Map<String,Id>();
            Id Accountrecordtype = [select Id From RecordType WHERE DeveloperName='Academic_Program'].Id;
                for(Account acc : [select id,Pardot_Program_Name__c,Name,SIS_Prog_Code__c from account where Name in : LeadPrimaryProgram1.values() AND RecordType.DeveloperName = 'Academic_Program' AND SIS_Prog_Code__c = null]){
                    accNamesToIdsMap1.put(acc.Name,acc.Id);
                }
            if (LeadPrimaryProgram1.containsKey(idKey)){

                string PrimaryProgram1=LeadPrimaryProgram1.get(idKey);
                if (accNamesToIdsMap1.containsKey(PrimaryProgram1)){          
                    Id AccountId1=accNamesToIdsMap1.get(PrimaryProgram1);
                    insertaffiliationList.add(new hed__Affiliation__c(hed__Account__c= AccountId1,
                                                            hed__Contact__c=insertConMap.get(IdKey).get(0).Id,
                                                            hed__Primary__c = true,
                                                            hed__Role__c='Prospect'));
                }
            }               
        }

        insert insertRelationShipList;
        insert insertaffiliationList;

        ConvertLeads(insertConMap);
    }
}
//method to convert the lead if lead has student details
public static void ConvertLeads1( Map<Id,List<Contact>> insertConMap1){

    LeadStatus Leads= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];

    Map<Id,Id> MapContactIdAccountId1 = new Map<Id,Id>(); //key: ContactID

    //Fetch AccountIds from database based on first contact for each Lead
    set<Id> PossibleContacts1 = new set<Id>();
    for(Id IdKey : insertConMap1.keySet()){
        PossibleContacts1.add(insertConMap1.get(IdKey).get(0).Id);
    }    

    for (Contact c:[select Id,AccountID from Contact where Id in :PossibleContacts1])
        MapContactIdAccountId1.put(c.id,c.AccountID);

    list<Database.LeadConvert> Leadconverts = new list<Database.LeadConvert>();

    for(Id IdKey : insertConMap1.keySet()){

        string ContactId=insertConMap1.get(IdKey).get(0).Id;
        string AccountId=MapContactIdAccountId1.get(ContactId);

        Database.LeadConvert Leadconvert = new Database.LeadConvert();
        Leadconvert.setLeadId(IdKey);                
        Leadconvert.setConvertedStatus(Leads.MasterLabel);
        Leadconvert.setAccountId(AccountId);
        Leadconvert.setContactId(ContactId);
        Leadconvert.setDoNotCreateOpportunity(TRUE); 
        Leadconverts.add(LeadConvert);
    }

    list<Database.LeadConvertResult> ConvertResults = Database.convertLead(Leadconverts);


}
//method to convert the lead if lead has student and parent details
public static void ConvertLeads( Map<Id,List<Contact>> insertConMap){

    LeadStatus Leads= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];

    Map<Id,Id> MapContactIdAccountId = new Map<Id,Id>(); //key: ContactID

    //Fetch AccountIds from database based on first contact for each Lead
    set<Id> PossibleContacts = new set<Id>();
    for(Id IdKey : insertConMap.keySet()){
        PossibleContacts.add(insertConMap.get(IdKey).get(0).Id);
    }    

    for (Contact c:[select Id,AccountID from Contact where Id in :PossibleContacts])
        MapContactIdAccountId.put(c.id,c.AccountID);

    list<Database.LeadConvert> Leadconverts = new list<Database.LeadConvert>();

    for(Id IdKey : insertConMap.keySet()){

        string ContactId=insertConMap.get(IdKey).get(0).Id;
        string AccountId=MapContactIdAccountId.get(ContactId);

        Database.LeadConvert Leadconvert = new Database.LeadConvert();
        Leadconvert.setLeadId(IdKey);                
        Leadconvert.setConvertedStatus(Leads.MasterLabel);
        Leadconvert.setAccountId(AccountId);
        Leadconvert.setContactId(ContactId);
        Leadconvert.setDoNotCreateOpportunity(TRUE); 
        Leadconverts.add(LeadConvert);
    }

    list<Database.LeadConvertResult> ConvertResults = Database.convertLead(Leadconverts);


}

public static Map<Id,List<Contact>> createContactParent(List<Lead> incomingLeadList){
    Id Studentrecordtype = [select Id From RecordType WHERE DeveloperName='Lead'].Id;
    Id Parentrecordtype = [select Id From RecordType WHERE DeveloperName='Parent'].Id;

    Map<Id, List<Contact>> contactMap = new Map<Id,List<Contact>>();
    List<Contact> conList=null;


    for(Lead tmpLead : incomingLeadList){
        string pickValuesStr;
        if(tmpLead.Other_Programs_of_Interest__c != null){
        List<string> pickvalues = tmpLead.Other_Programs_of_Interest__c.split(';');
        for(string str : pickvalues){
            if(string.isBlank(pickvaluesStr)){
                pickvaluesStr = str;
            }
            else{
                pickvaluesStr= pickvaluesStr+';'+str;
            }
        }
       }
            conList = new List<Contact>();
        Contact con = new Contact(
                LastName = tmpLead.LastName, 
                FirstName = tmpLead.FirstName,
                Email = tmpLead.Email,
                RecordTypeId = Studentrecordtype,
                );
            conList.add(con);

            con = new Contact(
                LastName = tmpLead.Parent_Last_Name__c,
                FirstName = tmpLead.Parent_First_Name__c,
                Email = tmpLead.Parent_Email__c,
                RecordTypeId = Parentrecordtype,
                Parent_is_alumni__c = tmpLead.Parent_is_alumni__c,
                Parent_Country_of_Residence__c = tmpLead.Parent_Country_of_Residence__c
            );
            conList.add(con);           
            contactMap.put(tmpLead.id, conList);
    }
    return contactMap;
}

public static Map<Id,List<Contact>> createContactNoParent(List<Lead> incomingLeadList){
    Map<Id, List<Contact>> contactMap1 = new Map<Id,List<Contact>>();
    Id Studentrecordtype = [select Id From RecordType WHERE DeveloperName='Lead'].Id;
    Id Parentrecordtype = [select Id From RecordType WHERE DeveloperName='Parent'].Id;

    List<Contact> contactList = null;
    for(Lead ldKey : incomingLeadList){
     string pickValuesStr1;
    if(ldKey.Other_Programs_of_Interest__c != null){               

    List<string> pickvalues = ldKey.Other_Programs_of_Interest__c.split(';');
        for(string str1 : pickvalues){
            if(string.isBlank(pickvaluesStr1)){
                pickvaluesStr1 = str1;
            }
            else{
                pickvaluesStr1= pickvaluesStr1+';'+str1;
            }
        }
    }
        contactList = new List<Contact>();
        Contact con = new Contact(
            LastName = ldKey.LastName,
            FirstName = ldKey.FirstName,
            Email =ldKey.Email,
            RecordTypeId = Studentrecordtype,
        );
        contactList.add(con);
        contactMap1.put(ldKey.Id, contactList);
    }
    return contactMap1;
}   
 }

Test Class:

@isTest
    public class TestContactCreationFromLead {

     static testMethod void ContactCreationFromLeadtrigger(){
Account acc = new Account(Name='Accounting and Finance',Pardot_Program_Name__c='Accounting and Finance');
insert acc;
Account acc1 = new Account(Name='Accounting and Finance',Pardot_Program_Name__c='Disability Studies');
insert acc1;
test.startTest();
  Lead le1 = new Lead(LastName='Lead1234', Email='[email protected]', Status='New',Company='Test',Expected_Year_of_Enrolment__c=2028,What_is_your_primary_program_of_interest__c='Accounting and Finance',Other_Programs_of_Interest__c='Accounting and Finance',Parent_or_guardian__c=false);
  insert le1;
Lead l1 = new Lead(LastName='Lead245', Email='[email protected]', Status='New',Company='Test',Expected_Year_of_Enrolment__c=2028,What_is_your_primary_program_of_interest__c='Accounting and Finance',Other_Programs_of_Interest__c='Accounting and Finance',Parent_First_Name__c='ParentF',Parent_Last_Name__c='ParentL',Parent_Email__c='[email protected]',Parent_or_guardian__c=true); 
  try{
  insert l1;
  }
  catch(Exception e){
      string errormessage = e.getMessage();
  }
  if(le1.Parent_or_guardian__c==false){
Contact c = new Contact(AccountId=acc.Id,LastName=le1.LastName,Email=le1.Email);
insert C;
   hed__Affiliation__c hed = new hed__Affiliation__c(hed__Account__c=acc.Id,hed__Contact__c=c.Id,hed__Primary__c=true);
    insert hed;
   hed__Affiliation__c hed1 = new hed__Affiliation__c(hed__Account__c=acc1.Id,hed__Contact__c=c.Id,hed__Primary__c=false);
    insert hed1;
}
  if(l1.Parent_or_guardian__c==true){
    Contact c1= new Contact(AccountId=acc.Id,LastName=l1.LastName,Email=l1.Email);
    update c1;
    Contact c2= new Contact(AccountId=acc.Id,LastName=l1.Parent_Last_Name__c,FirstName=l1.Parent_First_Name__c,Email=l1.Parent_Email__c);
    insert c2;
    hed__Affiliation__c hed2 = new hed__Affiliation__c(hed__Account__c=acc.Id,hed__Contact__c=c1.Id,hed__Primary__c=true);
    insert hed2;
    hed__Affiliation__c hed3 = new hed__Affiliation__c(hed__Account__c=acc1.Id,hed__Contact__c=c1.Id,hed__Primary__c=false);
    insert hed3;
    hed__Relationship__c rel = new hed__Relationship__c(hed__Contact__c=c1.Id,hed__RelatedContact__c=c2.Id,hed__Type__c='Parent');
    insert rel;
  }
le1 = [SELECT ConvertedAccountId FROM Lead WHERE Id = :le1.Id];
     System.assertNotEquals( le1.ConvertedAccountId, 'Expected lead to be converted.');
  l1 = [SELECT ConvertedAccountId FROM Lead WHERE Id = :l1.Id];
    System.assertNotEquals( l1.ConvertedAccountId, 'Expected lead to be converted.');
  test.stopTest();
 }
  }
4
  • Hi @Sainath and welcome to SFSE! Can I suggest you read the material in this general answer to such questions and if you still find you need help write a new question that shows you have done your research and that follows the recommendations in How to Ask. Thanks.
    – Phil W
    Commented Aug 7, 2019 at 9:05
  • @PhilW, I did tried in my way but failed to achieve then only I started posting it out here
    – Sainath
    Commented Aug 7, 2019 at 9:19
  • in that case, please add the code showing what you have tried to your question and explain what isn't working so people can help resolve specific issues. Asking the community to write the whole unit test for you from scratch isn't what SFSE is about.
    – Phil W
    Commented Aug 7, 2019 at 9:36
  • @PhilW, I added my test class to the question now, I am getting below error,can you help me out in this issue if possible. >System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LeadTrigger: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id 003P000001COBLjIAP; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Class.LeadTriggerHandler.afterInsertProcess: line 47, column 1 Trigger.LeadTrigger: line 3, column 1: []
    – Sainath
    Commented Aug 7, 2019 at 9:43

1 Answer 1

0

I am able to achieve it, I was inserting leads outside the starttest command, when I inserted leads inside starttest loop then it worked.

4
  • Good to hear. Note that you should consider bulkifying the inserts and updates in your unit tests. I'd also question why you have try/catch blocks in the test that do something other than verify that the code does or does not throw an exception in the appropriate conditions. Also, this isn't really a unit test as it doesn't actually perform any asserts to verify that the logic has correctly updated object state. Finally, you should avoid use of the deprecated testMethod keyword and use the (at)IsTest annotation instead.
    – Phil W
    Commented Aug 7, 2019 at 10:40
  • @PhilW, I did all the changes to the unit test code that you mentioned, then inside start test loop I inserted my leads, previous I inserted outside loop, when I inserted inside loop then it saved without issues and got 100% code coverage, thanks a lot for guiding me.
    – Sainath
    Commented Aug 7, 2019 at 11:55
  • Note that inserts inside loops are a bad thing - you are limited on the number of DML operations you can perform in a given test execution. Better to create all the required instances using a loop then do a single insert of the list of instances. This is what is meant by "bulkifying".
    – Phil W
    Commented Aug 7, 2019 at 12:21
  • 1
    exactly @PhilW, did same thing, created a list and added all the leads into list then inserted list using single insert.
    – Sainath
    Commented Aug 7, 2019 at 12:49

Not the answer you're looking for? Browse other questions tagged .