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
Sukriti SharmaSukriti Sharma 

Write a test class for CreateContact trigger

I wrote a trigger to either create or update the associated Contact when an Account is either create or updated. But how can I write one test class for it.
The trigger I made 
CreateContact.apxt
trigger CreateContact on Account (after insert, after update, before insert) {
    if(Trigger.isupdate && Trigger.isAfter){
        set<id> getaccountid =new set<id>();
        for(account acc : trigger.new){
        getaccountid.add(acc.id);
        system.debug(acc.id);
    }
    list<contact> conlist = [SELECT id, accountid from contact where accountid in:getaccountid];
    List<Contact> addCon = new List<Contact>();
    for(Contact cons : conlist){
        Account acc = Trigger.newmap.get(cons.accountid);
            cons.Lastname = acc.Name;
            cons.Fax = acc.Fax;
            cons.Phone = acc.Phone;
        	//cons.Email = acc.Email;
            cons.MailingStreet = acc.BillingStreet;
            cons.MailingCity = acc.BillingCity;
            cons.MailingCountry = acc.BillingCountry;
            addCon.add(cons);
        }
        update addCon;
    }
    if(Trigger.isinsert && Trigger.isbefore){
        List<Contact> addCon = new List<Contact>();
    	for(Account acc : trigger.new){
        //Account acc = Trigger.newmap.get(cons.accountid);
            if(acc.Create_Contact__c == true){
                Contact cons = new Contact();
            	cons.Lastname = acc.Name;
            	cons.Fax = acc.Fax;
            	cons.Phone = acc.Phone;
            	cons.MailingStreet = acc.BillingStreet;
            	cons.MailingCity = acc.BillingCity;
            	cons.MailingCountry = acc.BillingCountry;
            	addCon.add(cons);
            }
        }
        insert addCon;
    }
}

 
mukesh guptamukesh gupta
Hi Sukriti,

Please use below code:-
 
@isTest
public class CreateContactTest{

 testMethod static void createTest(){
		Account acc = new Account();
		acc.Name='Test Account' ;
		acc.Create_Contact__c = true;
		insert testAccount;
		
		Contact cont = new Contact();
		cont.FirstName='Test';
		cont.LastName='Test';
		cont.Accountid= testAccount.id;
		insert cont;
 }

}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
AnkaiahAnkaiah (Salesforce Developers) 
Hi Sukrithi,

try with below code.
@isTest
public class CreateContactTest{

 @Istest static void createTest(){
		Account acc = new Account();
		acc.Name='Test Account' ;
		acc.Create_Contact__c = true;
		insert acc;
		
		Contact con = new Contact();
		con.FirstName='Test';
		con.LastName='Test';
		con.Accountid= acc.id;
		insert con;
 }

}

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​