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
Luke DebritaLuke Debrita 

Code Coverage - Event data to Lead

Hello,

I have created the below trigger from events to write certain information to leads if event type criterea met:

1
2
3
4
5
6
7
8
9
10
11
12
13
trigger LeadUpdates on Event (before insert) {
  Set<Id> recordIds = new Set<Id>();
  List<Lead> leadsToUpdate = new List<Lead>();
      for(Event t:Trigger.new)
        if(t.type=='Discovery')
          recordIds.add(t.whoid);
      leadsToUpdate = [select id from lead where id in :recordIds];
          for(Lead l:leadsToUpdate)
            {L.SQL_Scheduled__c = TRUE;
             L.Status = '07 SQL';
             }
            update leadsToUpdate;
}

Here is the test class I wrote.  What am I missing?  When I validate the depoyment I get an error that there is 0% coverage for my trigger:


@isTest
public class testEventTrigger {
  static testMethod void test1() {
        // set up leads
        List<Lead> testLeads = new List<Lead>();
        Lead lead1 = new Lead();
        lead1.Company = 'Test 1 New Company';
        lead1.LastName = 'Martha';
        lead1.LeadSource = 'Not Converted';
        lead1.Status = '04 Sales Lead';
        lead1.Email = 'test@test.com';
        lead1.Business_Type__c = 'App/Business';
        lead1.Lead_Role__c = 'Product';
        testLeads.add(lead1);
        
        Lead lead2 = new Lead();
        lead2.Company = 'Test 12';
        lead2.LastName = 'Jordan';
        lead2.LeadSource = 'Not Converted';
        lead2.Status = '04 Sales Lead';
        lead2.Email = 'test@test.com';
        lead2.Business_Type__c = 'App/Business';
        lead2.Lead_Role__c = 'Product';
        testLeads.add(lead2);
    insert testLeads;
    
        // set up Events
       List<Event> events = new List<Event>();
       Event event1 = new Event();
       event1.WhoId=testLeads[0].Id; 
       event1.Subject= 'Test0';
       event1.Type='Discovery';
       event1.STARTDATETIME=System.today();
       event1.ENDDATETIME=System.today();

       Event event2 = new Event();
       event2.WhoId=testLeads[1].Id; 
       event2.Subject= 'Test1';
       event2.Type='Discovery';
       event2.STARTDATETIME=System.today();
       event2.ENDDATETIME=System.today();
    
    insert events;
    
    Map<Id,Lead> leadResults1 = new Map<Id,Lead>([select id,SQL_Scheduled__c from lead where id in :testLeads]);
    System.assertEquals(testLeads[1].SQL_Scheduled__c,leadResults1.get(testLeads[1].Id).SQL_Scheduled__c,TRUE);
    System.assertEquals(testLeads[0].SQL_Scheduled__c,leadResults1.get(testLeads[0].id).SQL_Scheduled__c,TRUE);
    
    Map<Id,Lead> leadResults2 = new Map<Id,Lead>([select id,Status from lead where id in :testLeads]);
    System.assertEquals(testLeads[1].Status,leadResults2.get(testLeads[1].Id).Status,'07 SQL');
    System.assertEquals(testLeads[0].Status,leadResults2.get(testLeads[0].id).Status,'07 SQL');
  }}
Best Answer chosen by Luke Debrita
Kevin CrossKevin Cross
Here is the updated Test code I used:
@isTest (seeAllData=false)
private class LeadUpdatesTest {
    static testMethod void testEventTrigger() {
        // set up leads
        List<Lead> testLeads = new List<Lead>();
        Lead lead1 = new Lead();
        lead1.Company = 'Test 1 New Company';
        lead1.LastName = 'Martha';
        lead1.LeadSource = 'Not Converted';
        lead1.Status = '04 Sales Lead';
        lead1.Email = 'test@test.com';
        //lead1.Business_Type__c = 'App/Business';
        //lead1.Lead_Role__c = 'Product';
        testLeads.add(lead1);
        
        Lead lead2 = new Lead();
        lead2.Company = 'Test 12';
        lead2.LastName = 'Jordan';
        lead2.LeadSource = 'Not Converted';
        lead2.Status = '04 Sales Lead';
        lead2.Email = 'test@test.com';
        //lead2.Business_Type__c = 'App/Business';
        //lead2.Lead_Role__c = 'Product';
        testLeads.add(lead2);
    	insert testLeads;
        
        // set up Events
        List<Event> events = new List<Event>();
        Event event1 = new Event();
        event1.WhoId=testLeads[0].Id; 
        event1.Subject= 'Test0';
        event1.Type='Discovery';
        event1.STARTDATETIME=System.today();
        event1.ENDDATETIME=System.today();
        events.add(event1);
        
        Event event2 = new Event();
        event2.WhoId=testLeads[1].Id; 
        event2.Subject= 'Test1';
        event2.Type='Discovery';
        event2.STARTDATETIME=System.today();
        event2.ENDDATETIME=System.today();
        events.add(event2);
    
        Test.startTest();
        insert events;
        Test.stopTest();
        
        List<Lead> leadResults = [SELECT /*SQL_Scheduled__c,*/ Status FROM Lead WHERE Id IN :testLeads];
        for (Lead l : leadResults) {
            //System.assertEquals(true, l.SQL_Scheduled__c);
            System.assertEquals('07 SQL', l.Status);
        }
    }
}

I commented out some of the custom fields to run this in my environment but otherwise, it should give you some ideas.  For example, notice you can do the assertions more simply but otherwise, the fix is the "events.add(...)" lines.

You can code this however it makes sense to you, but I also wanted to give you an example of what I meant about the FOR Loop.  Notice below, I finish the loop to add record Ids into Set<Id> then use it update leads.
trigger LeadUpdates on Event (before insert) {
    if (Trigger.isBefore && Trigger.isInsert) {
        Set<Id> leadIds = new Set<Id>();
        for (Event e : Trigger.new) {
            if (e.Type == 'Discovery') leadIds.add(e.WhoId);
        }
        if (leadIds.size() > 0) {
            List<Lead> leadsToUpdate = 
                [SELECT /*SQL_Scheduled__c,*/ Status FROM Lead WHERE Id IN :leadIds];
            for (Lead l : leadsToUpdate) {
                //l.SQL_Scheduled__c = true;
                l.Status = '07 SQL';
            }
            update leadsToUpdate;
        }
    }
}

Anyway, I hope that helps! 

Respectfully yours, Kevin

All Answers

Kevin CrossKevin Cross
Hello, Luke.

First, try wrapping your insert for the Event table with Test.startTest() like so this:
Test.startTest();
insert events;
Test.stopTest();

You also can check the permissions.  I have found that, although I am creating data within the Test class itself, that I still need to turn on the (seeAllData = true) option.

Hope that helps!

Respectfully yours, Kevin
Luke DebritaLuke Debrita
Thanks Kevin.

Just tried those two suggestions but still have 0% code coverage.  Is here something I need to do to create a referance between the trigger and test class?
Kevin CrossKevin Cross
Then that suggests that the trigger is not being executed, so you should check for code errors.  Note the Trigger code does not look correct as you are querying with the recordIds inside of loop.  The point of using a Set|List is to do operations in batch after the loop.  I also would double check that your test does not have any flaws in its logic by debugging what some of the values are before you get to your test position.

I will see if I can work up some specific examples of things to look for.
Kevin CrossKevin Cross
Okay.  For whatever reason I didn't see this until I put the code into a test environment.  You did not add the test events into the List<Event> you created.  Therefore, you never insert anything, which is why the Trigger never fires.
Kevin CrossKevin Cross
Here is the updated Test code I used:
@isTest (seeAllData=false)
private class LeadUpdatesTest {
    static testMethod void testEventTrigger() {
        // set up leads
        List<Lead> testLeads = new List<Lead>();
        Lead lead1 = new Lead();
        lead1.Company = 'Test 1 New Company';
        lead1.LastName = 'Martha';
        lead1.LeadSource = 'Not Converted';
        lead1.Status = '04 Sales Lead';
        lead1.Email = 'test@test.com';
        //lead1.Business_Type__c = 'App/Business';
        //lead1.Lead_Role__c = 'Product';
        testLeads.add(lead1);
        
        Lead lead2 = new Lead();
        lead2.Company = 'Test 12';
        lead2.LastName = 'Jordan';
        lead2.LeadSource = 'Not Converted';
        lead2.Status = '04 Sales Lead';
        lead2.Email = 'test@test.com';
        //lead2.Business_Type__c = 'App/Business';
        //lead2.Lead_Role__c = 'Product';
        testLeads.add(lead2);
    	insert testLeads;
        
        // set up Events
        List<Event> events = new List<Event>();
        Event event1 = new Event();
        event1.WhoId=testLeads[0].Id; 
        event1.Subject= 'Test0';
        event1.Type='Discovery';
        event1.STARTDATETIME=System.today();
        event1.ENDDATETIME=System.today();
        events.add(event1);
        
        Event event2 = new Event();
        event2.WhoId=testLeads[1].Id; 
        event2.Subject= 'Test1';
        event2.Type='Discovery';
        event2.STARTDATETIME=System.today();
        event2.ENDDATETIME=System.today();
        events.add(event2);
    
        Test.startTest();
        insert events;
        Test.stopTest();
        
        List<Lead> leadResults = [SELECT /*SQL_Scheduled__c,*/ Status FROM Lead WHERE Id IN :testLeads];
        for (Lead l : leadResults) {
            //System.assertEquals(true, l.SQL_Scheduled__c);
            System.assertEquals('07 SQL', l.Status);
        }
    }
}

I commented out some of the custom fields to run this in my environment but otherwise, it should give you some ideas.  For example, notice you can do the assertions more simply but otherwise, the fix is the "events.add(...)" lines.

You can code this however it makes sense to you, but I also wanted to give you an example of what I meant about the FOR Loop.  Notice below, I finish the loop to add record Ids into Set<Id> then use it update leads.
trigger LeadUpdates on Event (before insert) {
    if (Trigger.isBefore && Trigger.isInsert) {
        Set<Id> leadIds = new Set<Id>();
        for (Event e : Trigger.new) {
            if (e.Type == 'Discovery') leadIds.add(e.WhoId);
        }
        if (leadIds.size() > 0) {
            List<Lead> leadsToUpdate = 
                [SELECT /*SQL_Scheduled__c,*/ Status FROM Lead WHERE Id IN :leadIds];
            for (Lead l : leadsToUpdate) {
                //l.SQL_Scheduled__c = true;
                l.Status = '07 SQL';
            }
            update leadsToUpdate;
        }
    }
}

Anyway, I hope that helps! 

Respectfully yours, Kevin
This was selected as the best answer
Amit Chaudhary 8Amit Chaudhary 8
+1 Kevin Cross
I found below issue in your code
1) You was forget to perform DML for Event in your test class

Please check below post to learn about test classes
1) http://amitsalesforce.blogspot.in/search/label/Test%20Class
2) http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html

Please update your Test class like below
@isTest
public class testEventTrigger {
	static testMethod void test1() 
	{
        // set up leads
        List<Lead> testLeads = new List<Lead>();
        Lead lead1 = new Lead();
        lead1.Company = 'Test 1 New Company';
        lead1.LastName = 'Martha';
        lead1.LeadSource = 'Not Converted';
        lead1.Status = '04 Sales Lead';
        lead1.Email = 'test@test.com';
        lead1.Business_Type__c = 'App/Business';
        lead1.Lead_Role__c = 'Product';
        testLeads.add(lead1);
        
        Lead lead2 = new Lead();
        lead2.Company = 'Test 12';
        lead2.LastName = 'Jordan';
        lead2.LeadSource = 'Not Converted';
        lead2.Status = '04 Sales Lead';
        lead2.Email = 'test@test.com';
        lead2.Business_Type__c = 'App/Business';
        lead2.Lead_Role__c = 'Product';
        testLeads.add(lead2);
		insert testLeads;
    
		// set up Events
		List<Event> events = new List<Event>();
		Event event1 = new Event();
		event1.WhoId=testLeads[0].Id; 
		event1.Subject= 'Test0';
		event1.Type='Discovery';
		event1.STARTDATETIME=System.today();
		event1.ENDDATETIME=System.today();
		events.add(event1);
			
		Event event2 = new Event();
		event2.WhoId=testLeads[1].Id; 
		event2.Subject= 'Test1';
		event2.Type='Discovery';
		event2.STARTDATETIME=System.today();
		event2.ENDDATETIME=System.today();
		events.add(event2);
		insert events;
    
		List<Lead> leadResults1 = [select id,SQL_Scheduled__c,Status from lead where id in :testLeads];

		for(Lead led : leadResults1 )
		{
			System.assertEquals(led.SQL_Scheduled__c,TRUE);
			System.assertEquals(led.Status,'07 SQL');
		}
	}
}
Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required 
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you
 
Kevin CrossKevin Cross
Amit, thank you for the +1 but the DML to "insert events" is in both Luke's and my test classes.  The issue was he did not have the events.add(event1) and events.add(event2) originally.  Thanks for posting the information on Test classes, though.  I am sure it will be helping to others.
Luke DebritaLuke Debrita
Thank Kevin!  I used your code as the the framework for what I deployed.  Worked perfectly!