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
shakila Gshakila G 

How to write a test class for my new Trigger code?

I wrote a trigger to prevent task creation if customer Account is blocked.

This is my code,

trigger EventBlocked on Event (Before insert,after update) {
  
    list<Contact> clist =new list<Contact>();
    string Cname;
    
        for (Event t : Trigger.new) {
        
            if (t.WhoId !=Null) {
                
                clist= [select ID, Account_name__C, Account.Lock_record__C from Contact where 
                ID=:t.WhoId and Account.Lock_record__C=True]; 
                
            }
            
            IF(Clist.size()>0)
            {
            T.adderror('You Cant create a Event under the blocked Contact');
            }
            }
            }


How to write a test class for this trigger to improve the code coverage?
Raj VakatiRaj Vakati
@isTest
public class EventBlockedTest
{
    static testMethod void insertNewCalendarEvent()
    {
	
	Account acc = new Account();
	acc.Name ='Test';
	insert acc ;
	
	Contact con = new COntact();
	con.email='test@fmail.co';
	con.lastname='test' ;
	
	insert con;
	
	
        Test.StartTest();
        Event testEvent= new Event();
        testEvent.Subject = 'EventTest';
        testEvent.Location = 'Location';
        testEvent.Description = 'Description'; 
        testEvent.IsAllDayEvent=true;
		testEvent.WhoId= con.Id ;
        testEvent.StartDateTime =System.now();
        testEvent.EndDateTime = System.now()+10;
        insert testEvent;
        Test.StopTest();
    }
}

 
Aakanksha Singh 11Aakanksha Singh 11
Hello Shakila,

I hope this helps:
@isTest
private class EventBlockedTrigger {

    @isTest
    private static void testMeth(){
        account acc = new account(name='Test Account',Lock_record__c=true);
        insert acc;
        contact con = new contact(lastName='Test Contact',accountId=acc.id,Account_name__C='Test Account');
        insert con;
        try{
            Event ev = new event(WhoId= con.Id,DurationInMinutes=1,ActivityDateTime=system.now());
        	insert ev;
        }catch(exception e){
            system.debug(e);
        }
    }
    
}

For more Info on test class, you can visit this blog:
https://webkul.com/blog/test-classes-in-apex-salesforce/

Regards,
Aakanksha Singh
shakila Gshakila G
It's working fine. I have deployed my code to production.

Thank you so much.
Regards
Shakila
 
Amit Chaudhary 8Amit Chaudhary 8
Hi Shakila,

I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm

sample Test classes
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html


Always add Assert in your test class to validate the trigger result
@isTest
private class EventBlockedTest
{
    static testMethod void myUnitTest() 
    {
        Account acc = new Account(name='Test Account',Lock_record__c=true);
        insert acc;
		
        Contact con = new Contact(lastName='Test Contact',accountId=acc.id,Account_name__C='Test Account');
        insert con;
		
        try{
		
            Event ev = new event(WhoId= con.Id,DurationInMinutes=1,ActivityDateTime=system.now());
        	insert ev;
			
        }catch(exception e){
			
			Boolean expectedExceptionThrown =  e.getMessage().contains('You Cant create a Event under the blocked Contact')) ? true : false;
			System.AssertEquals(expectedExceptionThrown, true);

        }
    }
}

NOTE:- Even dnt use SOQL inside the for loop. try to update your trigger like below'
trigger EventBlocked on Event (Before insert,after update) {
  
	list<Contact> clist =new list<Contact>();
	string Cname;

	Set<Id> setWhoid = new Set<Id>():
	
	for (Event t : Trigger.new) {
		if (t.WhoId !=Null) 
		{
			setWhoid.add(t.WhoId);
		}
	}	
	
	Map<Id,Contact> mapCont = new Map<Id,Contact>( [ select ID, Account_name__C, Account.Lock_record__C from Contact where 
		ID in :setWhoid and Account.Lock_record__C=True ]);
	
	for (Event t : Trigger.new) {
		if (t.WhoId !=Null) 
		{
			IF(mapCont.containsKey(t.WhoId))
			{
				T.adderror('You Cant create a Event under the blocked Contact');
			}
		}
	}		
	
}


Let us know if this will help you