Can anyone help me out in writing test class for the below apex class.
I tried test class but when I was running the test then I am getting below error.
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LeadTrigger: execution of AfterInsert 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 003P000001CO0c0IAD; 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: []
Apex class:
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(){
List<Lead> parentleadinsert = new List<Lead>();
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(Id=le1.Id,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);
update l1;
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;
}
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);
update c2;
hed__Affiliation__c hed2 = new hed__Affiliation__c(hed__Account__c=acc.Id,hed__Contact__c=c1.Id,hed__Primary__c=true);
update hed2;
hed__Affiliation__c hed3 = new hed__Affiliation__c(hed__Account__c=acc1.Id,hed__Contact__c=c1.Id,hed__Primary__c=false);
update hed3;
hed__Relationship__c rel = new hed__Relationship__c(hed__Contact__c=c1.Id,hed__RelatedContact__c=c2.Id,hed__Type__c='Parent');
update 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();
}
}