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
Niraj Kumar 9Niraj Kumar 9 

Hi, test class, trigger handler needed while testing hits the SOQL query limits with test class code coverage is 61 percent only.

Hi guys,

Here is my Trigger::::::
 
trigger UpdateActivityCountonAccountContactOptyevent on Event (after insert, after delete) {

map<id,integer> mopportunityCount = new map<id,integer>();
  map<id,integer> maccountCount = new map<id,integer>();
  map<id,integer> mcontactCount = new map<id,integer>();
  
  Integer OptyCount = 0;
 Integer AccountCount = 0;
 Integer ContactCount = 0;
 
  if (trigger.isinsert){
   for(event e :trigger.new) {


    if(e.whoId != null) {
      if(string.valueOf(e.WhoId).left(3) == '003') {
         
         
         if(mcontactCount.containsKey(e.WhoId)) {
           ContactCount = mcontactCount.get(e.WhoId);
            }
         
         ContactCount = ContactCount + 1;
      
         mcontactCount.put(e.whoid,ContactCount);
      }
    }
  
    if(e.whatId != null) {
      if(string.valueOf(e.WhatId).left(3) == '006') {
         
         
         if(mopportunityCount.containsKey(e.WhatId)) {
           OptyCount = mopportunityCount.get(e.WhatId);
            }
         
         OptyCount = OptyCount + 1;
      
         mopportunityCount.put(e.whatid,OptyCount);
      }
      
    if(string.valueOf(e.WhatId).left(3) == '001') {
         
         
         if(maccountCount .containsKey(e.WhatId)) {
           AccountCount = maccountCount.get(e.WhatId);
            }
         
         AccountCount = AccountCount + 1;
      
         maccountCount.put(e.whatid,AccountCount);
      }
    }
   }
  }

  if (trigger.isdelete){
   for(event e :trigger.old) {


    if(e.whoId != null) {
      if(string.valueOf(e.WhoId).left(3) == '003') {
         
         
         if(mcontactCount.containsKey(e.WhoId)) {
           ContactCount = mcontactCount.get(e.WhoId);
            }
         
         ContactCount = ContactCount - 1;
      
         mcontactCount.put(e.whoid,ContactCount);
      }
    }
  
    if(e.whatId != null) {
      if(string.valueOf(e.WhatId).left(3) == '006') {
         
         
         if(mopportunityCount.containsKey(e.WhatId)) {
           OptyCount = mopportunityCount.get(e.WhatId);
            }
         
         OptyCount = OptyCount - 1;
      
         mopportunityCount.put(e.whatid,OptyCount);
      }
      
    if(string.valueOf(e.WhatId).left(3) == '001') {
         
         
         if(maccountCount .containsKey(e.WhatId)) {
           AccountCount = maccountCount.get(e.WhatId);
            }
         
         AccountCount = AccountCount - 1;
      
         maccountCount.put(e.whatid,AccountCount);
      }
    }
  }
 }
  if(mcontactCount.keyset().size()>0) {
    list<contact> contactToUpdate = new list<contact>([SELECT id,Count_of_Activity__c FROM contact WHERE Id IN :mcontactCount.keyset()]);

    for(contact o :contactToUpdate) {

        
    o.Count_of_Activity__c = o.Count_of_Activity__c + mcontactCount.get(o.id);
    }
   
    if(contactToUpdate.size()>0) {
      update contactToUpdate;
    }
   } 
 

  if(mopportunityCount.keyset().size()>0) {
    list<opportunity> opportunityToUpdate = new list<opportunity>([SELECT id,Count_of_Activity__c FROM opportunity WHERE Id IN :mopportunityCount.keyset()]);
     for(opportunity o :opportunityToUpdate ) {
     o.Count_of_Activity__c = o.Count_of_Activity__c + mopportunityCount.get(o.id);
    }
   if(opportunityToUpdate.size()>0) {
      update opportunityToUpdate;
    }
   } 
   if(maccountCount.keyset().size()>0) {
    list<account> accountToUpdate = new list<account>([SELECT id,Count_of_Activity__c FROM account WHERE Id IN :maccountCount.keyset()]);

    for(account a :accountToUpdate ) {

        
    a.Count_of_Activity__c = a.Count_of_Activity__c + maccountCount.get(a.id);
    }
   
    if(accountToUpdate.size()>0) {
      update accountToUpdate;
    }
   } 
  }
and Test class:::: if I used Contact instance hits governor limit of Soql .

@isTest (SeeAllData=true)
private class UpdateCountonAccountContactOptyeventTest{
   @isTest
    static void testMethodOne() {
    
    
    
       Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator' LIMIT 1];
      User u = new User(Alias = 'standt', Email='manasauser@thomsonreuters.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,  
      TimeZoneSidKey='America/Los_Angeles', UserName='manasauser@testorg.com', tfcrmTeamRole__c= 'Relationship Manager');

      System.runAs(u) {  
        
            Account testAccount1 = new Account(ShippingStreet='test',ShippingCity='test',ShippingPostalCode='123',ShippingCountry='United States');
            testAccount1.Name = 'FXall_Account1';
            testAccount1.trAccountClass__c='Global: F2FDirT';
            testAccount1.tfcmCountryCode__c = 'ATG';        
            insert testAccount1;  
             
             Event eve1 = new Event();
           eve1 .WhatId =testAccount1.Id;
          eve1 .subject='call';
          eve1 .StartDateTime = System.now();
          eve1.EndDateTime= System.now();
           eve1.Status__c = 'Cancelled';
           eve1.Type = 'Client Meeting';
           Insert eve1;
           
            Account accNew = [select  Count_of_Activity__c from Account where Id =: testAccount1.Id LIMIT 1];
        
        System.assertEquals(1, accNew.Count_of_Activity__c);
        
       
        
        
            
        
            
            opportunity opp1 = new Opportunity();
            opp1.NAME = 'opp1';
            opp1.AccountId = testAccount1.Id;
            opp1.CloseDate = system.today().addDays(14);
            opp1.Type = 'test';
            opp1.tfcrmMkt__c='Corporate Route';
            opp1.StageName = Label.Opportunity_Stage_6;
            opp1.PROBABILITY = 10.0;
            opp1.TOCEXPECTEDREVENUEDATE__C = system.today().addDays(40);
            opp1.TFCRMMKT__C = 'Reuters';
            opp1.TFCRMGLOBALDEAL__C = false;
            opp1.TFCRMTYPE__C = 'Notified Cancellation';
            opp1.tfcrmWinLossReason__c= 'Community/Connectivity';
            opp1.tfcrmWinLossCommentary__c= 'Sample';
            opp1.Current_Competitive_System__c= 'Sample';
            opp1.Lost_to_Competitor__c= 'Sample';
            opp1.Competitors__c= 'Actimize';
            opp1.PriceBook2Id= Label.Opportunity_Pricebook2Id;       
             
            insert opp1;  
            
            
        
         Event eve = new Event();
         eve .WhatId =opp1.Id;
          eve .subject='call';
          eve .StartDateTime = System.now();
          eve .EndDateTime= System.now();
           eve.Status__c = 'In Progress';
           eve.Type = 'Client Meeting';
          
           Insert eve;
          
            
        Opportunity oppNew = [select Count_of_Activity__c from Opportunity where Id =: opp1.Id LIMIT 1];
        
        System.assertEquals(1, oppNew.Count_of_Activity__c);
           
             delete eve;
                 
        Opportunity oppNew1 = [select Count_of_Activity__c from Opportunity where Id =: opp1.Id LIMIT 1];
        
        System.assertEquals(0, oppNew1.Count_of_Activity__c);
        
        
         
             Contact con = new Contact();
            con.AccountId=testAccount1.Id;
            con.FirstName='Dummy';
            con.LastName='Test';
            con.Salutation='Mr.';
            con.Phone='12345678';
            con.Email='dummytest1@thomsonreuters.com';
            insert con;    
            
          
        
         Event eve2 = new Event();
         eve2.WhoId =con.Id;
          eve2 .subject='call';
          eve2.StartDateTime = System.now();
          eve2.EndDateTime= System.now();
           eve2.Status__c = 'In Progress';
           eve2.Type = 'Client Meeting';
          
           Insert eve;
          
            
        Contact conNew = [select Id, Count_of_Activity__c from Contact where Id =: con.Id];
        
        System.assertEquals(1, conNew.Count_of_Activity__c);
          
        
        
         
          
         
        
        
     
        
      }  
        
    }
}
 
Best Answer chosen by Niraj Kumar 9
John Pipkin 14John Pipkin 14
Niraj, 

Please try this test class:
@isTest
private class UpdateCountonAccountContactOptyeventTest{

    @TestMethod static void buildTestData(){
        Account testAccount1 = new Account(ShippingStreet='test',ShippingCity='test',ShippingPostalCode='123',ShippingCountry='United States');
        testAccount1.Name = 'FXall_Account1';
        testAccount1.trAccountClass__c='Global: F2FDirT';
        testAccount1.tfcmCountryCode__c = 'ATG';        
        insert testAccount1;  

    }

       
    static testMethod void testMethodOne() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator' LIMIT 1];
           User u = new User(Alias = 'standt', Email='manasauser@thomsonreuters.com',
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
          LocaleSidKey='en_US', ProfileId = p.Id,  
          TimeZoneSidKey='America/Los_Angeles', UserName='manasauser@testorg.com', tfcrmTeamRole__c= 'Relationship Manager');

           Account testAccount1 = [Select Id from Account];
           Test.startTest();
          System.runAs(u) {  
             Event eve1 = new Event();
               eve1.WhatId = testAccount1.Id;
              eve1.subject='call';
              eve1.StartDateTime = System.now();
              eve1.EndDateTime= System.now();
               eve1.Status__c = 'Cancelled';
               eve1.Type = 'Client Meeting';
               Insert eve1;
               Test.stopTest();
            Account accNew = [select  Count_of_Activity__c from Account where Id =: testAccount1.Id LIMIT 1];
        
            System.assertEquals(1, accNew.Count_of_Activity__c);
        }
    }

    static testMethod void testMethodTwo(){
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator' LIMIT 1];
           User u = new User(Alias = 'standt', Email='manasauser@thomsonreuters.com',
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
          LocaleSidKey='en_US', ProfileId = p.Id,  
          TimeZoneSidKey='America/Los_Angeles', UserName='manasauser@testorg.com', tfcrmTeamRole__c= 'Relationship Manager');

        Account testAccount1 = [Select Id from Account];
        Test.startTest();
        System.runAs(u){   
            opportunity opp1 = new Opportunity();
            opp1.NAME = 'opp1';
            opp1.AccountId = testAccount1.Id;
            opp1.CloseDate = system.today().addDays(14);
            opp1.Type = 'test';
            opp1.tfcrmMkt__c='Corporate Route';
            opp1.StageName = Label.Opportunity_Stage_6;
            opp1.PROBABILITY = 10.0;
            opp1.TOCEXPECTEDREVENUEDATE__C = system.today().addDays(40);
            opp1.TFCRMMKT__C = 'Reuters';
            opp1.TFCRMGLOBALDEAL__C = false;
            opp1.TFCRMTYPE__C = 'Notified Cancellation';
            opp1.tfcrmWinLossReason__c= 'Community/Connectivity';
            opp1.tfcrmWinLossCommentary__c= 'Sample';
            opp1.Current_Competitive_System__c= 'Sample';
            opp1.Lost_to_Competitor__c= 'Sample';
            opp1.Competitors__c= 'Actimize';
            opp1.PriceBook2Id= Label.Opportunity_Pricebook2Id;       
             
            insert opp1;  
            
             Event eve = new Event();
             eve .WhatId =opp1.Id;
              eve .subject='call';
              eve .StartDateTime = System.now();
              eve .EndDateTime= System.now();
               eve.Status__c = 'In Progress';
               eve.Type = 'Client Meeting';
          
               Insert eve;
              
            Opportunity oppNew = [select Count_of_Activity__c from Opportunity where Id =: opp1.Id LIMIT 1];
            System.assertEquals(1, oppNew.Count_of_Activity__c);
            delete eve;
            Test.stopTest();
                 
            Opportunity oppNew1 = [select Count_of_Activity__c from Opportunity where Id =: opp1.Id LIMIT 1];
            System.assertEquals(0, oppNew1.Count_of_Activity__c);
        }
    }

    static testMethod void testMethodThree(){
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator' LIMIT 1];
           User u = new User(Alias = 'standt', Email='manasauser@thomsonreuters.com',
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
          LocaleSidKey='en_US', ProfileId = p.Id,  
          TimeZoneSidKey='America/Los_Angeles', UserName='manasauser@testorg.com', tfcrmTeamRole__c= 'Relationship Manager');

        Account testAccount1 = [Select Id from Account];
        Test.startTest();
        System.runAs(u){    
            
            Contact con = new Contact();
            con.AccountId=testAccount1.Id;
            con.FirstName='Dummy';
            con.LastName='Test';
            con.Salutation='Mr.';
            con.Phone='12345678';
            con.Email='dummytest1@thomsonreuters.com';
            insert con;  

             Event eve2 = new Event();
             eve2.WhoId =con.Id;
              eve2 .subject='call';
              eve2.StartDateTime = System.now();
              eve2.EndDateTime= System.now();
               eve2.Status__c = 'In Progress';
               eve2.Type = 'Client Meeting';
          
               Insert eve;
              Test.stopTest();
            
            Contact conNew = [select Id, Count_of_Activity__c from Contact where Id =: con.Id];
        
            System.assertEquals(1, conNew.Count_of_Activity__c);
        }
    }
}

 

All Answers

John Pipkin 14John Pipkin 14
Niraj, 

The trigger you posted looks fine. There may be a query in a for loop in one of the other triggers or you have some recursive updates going on. I would split the test class into 3 separate methods. One for each object you are checking. If that doesn't work, check out the debug logs to see if triggers are being run more times than they should.
Prem Anandh 1Prem Anandh 1
Hi Niraj, 

Please check any recursion is occuring on this trigger. Also, update SeeAllData=false from true and try.
Niraj Kumar 9Niraj Kumar 9
Hi Guys,

hitting the SOQL limits.
Niraj Kumar 9Niraj Kumar 9
Hi,

test class hitting soql limitation and failed to Dml operation on line::::     insert con; 
please help me...
Thanks in advance.
 
Niraj Kumar 9Niraj Kumar 9
Hi,

I need the trigger handler class. Can Anyone modified my code with test class?

Best regards,
Niraj Kumar
John Pipkin 14John Pipkin 14
Niraj, 

Please try this test class:
@isTest
private class UpdateCountonAccountContactOptyeventTest{

    @TestMethod static void buildTestData(){
        Account testAccount1 = new Account(ShippingStreet='test',ShippingCity='test',ShippingPostalCode='123',ShippingCountry='United States');
        testAccount1.Name = 'FXall_Account1';
        testAccount1.trAccountClass__c='Global: F2FDirT';
        testAccount1.tfcmCountryCode__c = 'ATG';        
        insert testAccount1;  

    }

       
    static testMethod void testMethodOne() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator' LIMIT 1];
           User u = new User(Alias = 'standt', Email='manasauser@thomsonreuters.com',
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
          LocaleSidKey='en_US', ProfileId = p.Id,  
          TimeZoneSidKey='America/Los_Angeles', UserName='manasauser@testorg.com', tfcrmTeamRole__c= 'Relationship Manager');

           Account testAccount1 = [Select Id from Account];
           Test.startTest();
          System.runAs(u) {  
             Event eve1 = new Event();
               eve1.WhatId = testAccount1.Id;
              eve1.subject='call';
              eve1.StartDateTime = System.now();
              eve1.EndDateTime= System.now();
               eve1.Status__c = 'Cancelled';
               eve1.Type = 'Client Meeting';
               Insert eve1;
               Test.stopTest();
            Account accNew = [select  Count_of_Activity__c from Account where Id =: testAccount1.Id LIMIT 1];
        
            System.assertEquals(1, accNew.Count_of_Activity__c);
        }
    }

    static testMethod void testMethodTwo(){
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator' LIMIT 1];
           User u = new User(Alias = 'standt', Email='manasauser@thomsonreuters.com',
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
          LocaleSidKey='en_US', ProfileId = p.Id,  
          TimeZoneSidKey='America/Los_Angeles', UserName='manasauser@testorg.com', tfcrmTeamRole__c= 'Relationship Manager');

        Account testAccount1 = [Select Id from Account];
        Test.startTest();
        System.runAs(u){   
            opportunity opp1 = new Opportunity();
            opp1.NAME = 'opp1';
            opp1.AccountId = testAccount1.Id;
            opp1.CloseDate = system.today().addDays(14);
            opp1.Type = 'test';
            opp1.tfcrmMkt__c='Corporate Route';
            opp1.StageName = Label.Opportunity_Stage_6;
            opp1.PROBABILITY = 10.0;
            opp1.TOCEXPECTEDREVENUEDATE__C = system.today().addDays(40);
            opp1.TFCRMMKT__C = 'Reuters';
            opp1.TFCRMGLOBALDEAL__C = false;
            opp1.TFCRMTYPE__C = 'Notified Cancellation';
            opp1.tfcrmWinLossReason__c= 'Community/Connectivity';
            opp1.tfcrmWinLossCommentary__c= 'Sample';
            opp1.Current_Competitive_System__c= 'Sample';
            opp1.Lost_to_Competitor__c= 'Sample';
            opp1.Competitors__c= 'Actimize';
            opp1.PriceBook2Id= Label.Opportunity_Pricebook2Id;       
             
            insert opp1;  
            
             Event eve = new Event();
             eve .WhatId =opp1.Id;
              eve .subject='call';
              eve .StartDateTime = System.now();
              eve .EndDateTime= System.now();
               eve.Status__c = 'In Progress';
               eve.Type = 'Client Meeting';
          
               Insert eve;
              
            Opportunity oppNew = [select Count_of_Activity__c from Opportunity where Id =: opp1.Id LIMIT 1];
            System.assertEquals(1, oppNew.Count_of_Activity__c);
            delete eve;
            Test.stopTest();
                 
            Opportunity oppNew1 = [select Count_of_Activity__c from Opportunity where Id =: opp1.Id LIMIT 1];
            System.assertEquals(0, oppNew1.Count_of_Activity__c);
        }
    }

    static testMethod void testMethodThree(){
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator' LIMIT 1];
           User u = new User(Alias = 'standt', Email='manasauser@thomsonreuters.com',
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
          LocaleSidKey='en_US', ProfileId = p.Id,  
          TimeZoneSidKey='America/Los_Angeles', UserName='manasauser@testorg.com', tfcrmTeamRole__c= 'Relationship Manager');

        Account testAccount1 = [Select Id from Account];
        Test.startTest();
        System.runAs(u){    
            
            Contact con = new Contact();
            con.AccountId=testAccount1.Id;
            con.FirstName='Dummy';
            con.LastName='Test';
            con.Salutation='Mr.';
            con.Phone='12345678';
            con.Email='dummytest1@thomsonreuters.com';
            insert con;  

             Event eve2 = new Event();
             eve2.WhoId =con.Id;
              eve2 .subject='call';
              eve2.StartDateTime = System.now();
              eve2.EndDateTime= System.now();
               eve2.Status__c = 'In Progress';
               eve2.Type = 'Client Meeting';
          
               Insert eve;
              Test.stopTest();
            
            Contact conNew = [select Id, Count_of_Activity__c from Contact where Id =: con.Id];
        
            System.assertEquals(1, conNew.Count_of_Activity__c);
        }
    }
}

 
This was selected as the best answer
Niraj Kumar 9Niraj Kumar 9
Hi,

Scenari is that field count of Activity is in Account, contact, opportunity. Trigger helps to me to count the activity of Account, opportunity, Contact separately.
 
Niraj Kumar 9Niraj Kumar 9
hi,

giving error on line :::: Account testAccount1 = [Select Id from Account]; Error is List has no rows for assignment to SObject
John Pipkin 14John Pipkin 14
Sorry about that. The first method should be 
@TestSetup static void buildTestData(){
        Account testAccount1 = new Account(ShippingStreet='test',ShippingCity='test',ShippingPostalCode='123',ShippingCountry='United States');
        testAccount1.Name = 'FXall_Account1';
        testAccount1.trAccountClass__c='Global: F2FDirT';
        testAccount1.tfcmCountryCode__c = 'ATG';        
        insert testAccount1;  

    }

 
Niraj Kumar 9Niraj Kumar 9
Hi John,

Thanks for the reply.

Good news :: Now its working perfectly.

One more support needed,,Can u please give me the method of test class ?

One again Thanks.


Best regards,

Niraj

 
John Pipkin 14John Pipkin 14
Niraj, what do you mean by "give me the method of test class"?
Niraj Kumar 9Niraj Kumar 9
Hi John,

For example, @TestSetup like that.

Best Regards,
Niraj
Niraj Kumar 9Niraj Kumar 9
Hi John,

Sorry, Its not a method . Its only annotation.
John Pipkin 14John Pipkin 14
@TestSetup is used for setting up data for test methods inside a test class. See http://jessealtman.com/2015/01/new-spring-15-feature-testsetup/  for more details about it.