I have created this following class and test class below. My question is in my class in Line X(commented line X) if i use that instead of Line Y I am receiving the above mentioned error. I put the debug logs and noticed that as the loop continues to add contacts to the list the Account Id for all the contacts so far in the list is being updated to the current Account Id that is being looped but if i use the Line Y this is not the case.
The Line X way is ultimately creating a new instance of Contact record with some prepopulated values right? Appreciate the clarification.
Class:
public class AddPrimaryContact implements Queueable {
Contact con = new Contact();
String state;
//List<Contact> conList;
public AddPrimaryContact(Contact conArgu, String stateArgu){
this.con = conArgu;
this.state = stateArgu;
}
public void execute(QueueableContext context) {
//String stateLoc = this.state;
List<Account> accList = new List<Account>([SELECT Id FROM Account WHERE BillingState = :state LIMIT 200]);
List<Contact> conList = new List<Contact>();
for(Account acc : accList){
//Contact newCon = (Contact)con; // Line X
Contact newCon = con.clone(false,false,false,false); // Line Y
newCon.AccountId = acc.Id;
conList.add(newCon);
system.debug(conList);
}
insert conList;
}
}
Here is my test class:
@isTest
public class AddPrimaryContactTest {
@isTest static void testAccountInsert() {
List<Account> testAccList = new List<Account>();
List<Account> testAccList1 = new List<Account>();
//String AccState = 'IL'
for(integer i =0; i< 100; i++){
if(i < 50){
Account acc = new Account(Name = 'Test' + i, BillingState = 'NY');
testAccList.add(acc);
}
else{
Account acc = new Account(Name = 'Test' + i, BillingState = 'CA');
testAccList1.add(acc);
}
}
insert testAccList;
insert testAccList1;
Contact con = new Contact(LastName = 'testCon');
insert con;
AddPrimaryContact apc = new AddPrimaryContact(con, 'NY');
AddPrimaryContact apc1 = new AddPrimaryContact(con, 'CA');
Test.startTest();
System.enqueueJob(apc);
System.enqueueJob(apc1);
Test.stopTest();
System.assertEquals(50, [SELECT count() FROM Contact WHERE AccountId IN :testAccList1]);
}
}