Home SALESFORCEAPEX Create an Queueable Apex class that inserts Contacts for Accounts – Queueable Apex

Create an Queueable Apex class that inserts Contacts for Accounts – Queueable Apex

Create an Queueable Apex class that inserts Contacts for Accounts.

Create a Queueable Apex class that inserts the same Contact for each Account for a specific state. Write unit tests that achieve 100% code coverage for the class.

  • Create an Apex class called ‘AddPrimaryContact’ that implements the Queueable interface.
  • Create a constructor for the class that accepts as its first argument a Contact sObject and a second argument as a string for the State abbreviation.
  • The execute method must query for a maximum of 200 Accounts with the BillingState specified by the State abbreviation passed into the constructor and insert the Contact sObject record associated to each Account. Look at the sObject clone() method.
  • Create an Apex test class called ‘AddPrimaryContactTest’.
  • In the test class, insert 50 Account records for BillingState “NY” and 50 Account records for BillingState “CA”. Create an instance of the AddPrimaryContact class, enqueue the job and assert that a Contact record was inserted for each of the 50 Accounts with the BillingState of “CA”.
  • The unit tests must cover all lines of code included in the AddPrimaryContact class, resulting in 100% code coverage.
  • Run your test class at least once (via ‘Run All’ tests the Developer Console) before attempting to verify this challenge.

Code Example:

AddPrimaryContact – Apex Class

public class AddPrimaryContact implements Queueable {
public contact c;
public String state;

public AddPrimaryContact(Contact c, String state) {
this.c = c;
this.state = state;

public void execute(QueueableContext qc) {
system.debug(‘this.c = ‘+this.c+’ this.state = ‘+this.state);
List<Account> accList = new List<account>([select id, name, BillingState from account where account.BillingState = :this.state limit 200]);
List<contact> insertContact = new List<contact>();
for(account a: accList) {
contact c = new contact();
c = this.c.clone(false, false, false, false);
c.AccountId = a.Id;
insert insertContact;


AddPrimaryContactTest – Apex Test Class

public class AddPrimaryContactTest {

static void setup() {
List<Account> insertAccount = new List<Account>();
for(integer i=0; i<=100; i++) {
if(i <=50) {
insertAccount.add(new Account(Name=’Acc’+i, BillingState = ‘NY’));
} else {
insertAccount.add(new Account(Name=’Acc’+i, BillingState = ‘CA’));
insert insertAccount;

static testMethod void testAddPrimaryContact() {
Contact con = new Contact(LastName = ‘LastName’);
AddPrimaryContact addPC = new AddPrimaryContact(con, ‘CA’);

system.assertEquals(50, [select count() from Contact]);


You may also like

Leave a Comment