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
Salesforce Admin2Salesforce Admin2 

How to write a trigger test class to help get my code coverage up to 75%

trigger CaseCommentValidate on CaseComment (before delete, before update) {
      Id profileId=userinfo.getProfileId();
    String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
    system.debug('ProfileName'+profileName);
       
     if (Trigger.isDelete) {
          for (CaseComment caseComment : Trigger.old) {
             Case parentCase = [Select Id, Parks__c, Works__c, Returned_Date__c from Case where Id =:caseComment.parentId];
             if((parentCase.Works__c== TRUE || parentCase.Parks__c == TRUE) && parentCase.Returned_Date__c == null && profileName != 'System Administrator')  {
                 caseComment.addError('Comments cannot be deleted on cases being integrated with ...');
             }      
          }
     }
     else   {
           for (CaseComment caseComment : Trigger.new) {
               CaseComment oldCaseComment  = Trigger.oldMap.get(caseComment.ID);
               Case parentCase = [Select status , Id, Parks__c, Works__c, Returned_Date__c from Case where Id =:caseComment.parentId];
               if((parentCase.Works__c== TRUE || parentCase.Parks__c == TRUE) && parentCase.Returned_Date__c == null && profileName != 'System Administrator')  {
                   if(caseComment.CommentBody != oldCaseComment.CommentBody)
                      caseComment.addError('Comments cannot be changed on cases being integrated with ...');
               }      
            }
     }          
}
I need a test class for the above trigger but not sure how to write it to help get my code cover upto 75%.  Right now my code coverage is at 67% when trying to deploy to production. 
Anupam RastogiAnupam Rastogi
Share your existing Test Class that is giving you 67% coverage.
Salesforce Admin2Salesforce Admin2
Hi Anupam, here is a Test Class that is giving 72% code coverage when tested in the sandbox test env. but when I actually attemp to deploy my trigger in the production environment I am only getting 67% code coverage. Whatever help, suggestions you can give  me will be much appreciated.  Thank You
@isTest
public class TestCaseAssignment {
   static  testmethod void insertNewcase() {
   List<Case> cases = new List<Case>();
    for(integer i = 0 ; i< 20 ; i++)
    {
        Case joe = new Case();
        joe.Service_Request_Type__c  = 'Miscellaneous';
        joe.Status = 'New';
        joe.Origin = 'Phone';
        joe.Priority = 'Medium';
        joe.Location_Format__c='Street Address';
        joe.Street_Name__c='LINCOLN ST';
        joe.Street_Number__c='230';
        cases.add(joe);
    }
    Database.insert(cases);
  }
}
                              
Anupam RastogiAnupam Rastogi
The Trigger has a IF statement for Delete, but the Test Class in not having any code for casecomment deletion. Include a piece of code that deletes a case comment so that the corresponding IF statement of the Trigger is also covered.

Moreover, I would suggest that you create a case such that it satisfy the conditions when the Case Comment is updated or deleted.
1. Update the Case Comment
2. Delete the Case Comment

This should trigger the two IF and ELSE statements sequentially and help you increase the Code Coverage.

Thanks
AR
Salesforce Admin2Salesforce Admin2
Hi Anupam, I have written the below test trigger based on your suggestion.  I will test it out today.  Check out my test class below and let me know what you think.  You are awesome!  Thank you so much for your support Anupam! Frances

@istest public with sharing class CaseTriggerTestfl{
    public static testmethod void testCaseTrigger()
    {
        //When a new case (First Case) is created
        case cs = new case();
        cs.Subject= 'Testing';
        cs.Origin='Phone';
        cs.Description = 'FL Testing Triggers calls';
        cs.Status ='Open';
        cs.Location_Format__c='Street Address';
        cs.Street_Name__c='LINCOLN ST';
        cs.Street_Number__c='230';
        cs.Send_Case_Creation_Email_to_Contact__c=False;
       
        insert cs; 
       
              

        casecomment ccom = new casecomment ();
        ccom.commentBody = cs.Description;
        ccom.parentid = cs.id;
        insert ccom;
       
        cs.Send_Case_Creation_Email_to_Contact__c=True;  //the updating of the send case creation email  to contact checkbox should trigger the HandleLucityFieldUpdate trigger
        update cs;

       
        delete ccom;   //the deleting the comments should trigger the LucityCaseCommentValidate trigger
       
       
        delete cs;    // deleting the case should trigger the LucityCaseValidation trigger
       
    }
        }
Salesforce Admin2Salesforce Admin2
The Apex Test Execution for All namespace in the test environment returned 64% code coverage.  The above test class didn't increase my code coverage in the testing environment.  Back to the drawing board. 
Anupam RastogiAnupam Rastogi
Hi,

I used your Trigger and Test Class codes, created the custom fields and ran the Tests. You know what - I was able to achieve 100% code coverage :) I hope it gives the same results to you too.

Remember that you run the Test class with a profile other than System Administrator.

Here is the modified Test Class. Just copy and perform a Test run. 
@istest public with sharing class CaseTriggerTestfl{
    public static testmethod void testCaseTrigger()
    {
        //When a new case (First Case) is created
        case cs = new case();
        cs.Subject= 'Testing';
        cs.Origin='Phone';
        cs.Description = 'FL Testing Triggers calls';
        cs.Status ='Open';
        cs.Works__c = True;

        /*--- Commented fields that are not used in the Trigger. If any of these fields are mandatory without which the Case record won't save then you can un-comment that field.
        cs.Location_Format__c='Street Address';
        cs.Street_Name__c='LINCOLN ST';
        cs.Street_Number__c='230';
        cs.Send_Case_Creation_Email_to_Contact__c=False;*/
        
        insert cs; 

        casecomment ccom = new casecomment ();
        ccom.commentBody = cs.Description;
        ccom.parentid = cs.id;
        insert ccom;
        
        try {
        	ccom.CommentBody = 'Changed the Description 1';
        	update ccom;
        }
        catch (Exception e) {
            
            Boolean exceptionThrown = e.getMessage().contains('Comments cannot be changed on cases being integrated with ...')? true : false;
            System.assertEquals(exceptionThrown, true);
        }
        
        try {
        	delete ccom;
        }
        catch (Exception e) {
            
            Boolean exceptionThrown = e.getMessage().contains('Comments cannot be deleted on cases being integrated with ...')? true : false;
            System.assertEquals(exceptionThrown, true);
        }        
        //delete cs;    // deleting the case should trigger the LucityCaseValidation trigger
    }
}

There are no changes done to the Trigger code.

Thanks
AR

If you found the reply useful that solved your problem then please mark it as best answer.
Salesforce Admin2Salesforce Admin2
Hi Anupam, I ran the above script and I have started receiving a Class.CaseTriggerTestfl.testCaseTrigger: line 16, column 1 (insert cs; ) erro.   It is line 18 in the above script.  The test script that use to run is not working anymore.  Do you have any suggestions on what to check in my test environment that may have caused the insert function to stop working in my test script?  Thank You
Anupam RastogiAnupam Rastogi
Hi,

I guess the lines of code that I commented is causing this issue. Can you share the list of fields that are mandatory on the Case Object in your test environment.

Meanwhile, try the following Test Class and see if it runs successfully. I have uncommented the lines I commented earlier.
 
@istest public with sharing class CaseTriggerTestfl{
    public static testmethod void testCaseTrigger()
    {
        //When a new case (First Case) is created
        case cs = new case();
        cs.Subject= 'Testing';
        cs.Origin='Phone';
        cs.Description = 'FL Testing Triggers calls';
        cs.Status ='Open';
        cs.Works__c = True;
        cs.Location_Format__c='Street Address';
        cs.Street_Name__c='LINCOLN ST';
        cs.Street_Number__c='230';
        cs.Send_Case_Creation_Email_to_Contact__c=False;
        
        insert cs; 

        casecomment ccom = new casecomment ();
        ccom.commentBody = cs.Description;
        ccom.parentid = cs.id;
        insert ccom;
        
        try {
        	ccom.CommentBody = 'Changed the Description 1';
        	update ccom;
        }
        catch (Exception e) {
            
            Boolean exceptionThrown = e.getMessage().contains('Comments cannot be changed on cases being integrated with ...')? true : false;
            System.assertEquals(exceptionThrown, true);
        }
        
        try {
        	delete ccom;
        }
        catch (Exception e) {
            
            Boolean exceptionThrown = e.getMessage().contains('Comments cannot be deleted on cases being integrated with ...')? true : false;
            System.assertEquals(exceptionThrown, true);
        }        
        //delete cs;    // deleting the case should trigger the LucityCaseValidation trigger
    }
}

Let me know the results. Also share the error, if any after this new test run, with the details.

Thanks
AR
Salesforce Admin2Salesforce Admin2
Hi Anupam, I had all the lines uncommented when I did the test.  Sorry I fail to tell you the above script ran successful the first time but I didn't get the 100 percent code coverage, So I started working on the test script some more in hopes to get the 100 percent code coverage instead I started getting failures.  So I went back to the orginal script above.

, the error I am getting is System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LucityCaseInsertion: execution of AfterInsert

caused by: line 15, column 61: trigger body is invalid and failed recompilation: Dependent class is invalid and needs recompilation:
insertcaseinlucity: class failed previous initial parse attempt: []   

Not sure why the error is stating my trigger is invalid and failed recompilation because no changes has been made to the trigger since I have bee testing,  I will try to recompile the trigger and see what happens.  Any suggestions you have I would appreciate it.  Than You
Anupam RastogiAnupam Rastogi
Hi,

The error seems to be in your other Tigger 'LucityCaseInsertion'. 

Therefore I strongly recommend you to do the following step by step - 

1. First to test the current Tigger 'CaseCommentValidate', you can comment out the erroring Trigger 'LucityCaseInsertion'. I am pretty sure that after commenting the erroring Trigger, the other Trigger in discussion will work properly giving decent code coverage.

2. Once we are successful in the first step, then you can share the code for Trigger 'LucityCaseInsertion' along with any Test Class that you have written for it. We can look into getting it right.

Let me know how to think about this approach.

Thanks
AR
Salesforce Admin2Salesforce Admin2
Hi Anupam,

I finally figured my issue in the CaseTestTrigger Class. I added a field name named Lucity_WR_ID in the case script because I was trying to get a higher code coverage in the CaseCommentValidate Trigger.  Come to find out I was going after the Lucity_WR_ID field incorrectly in the CaseTestTrigger class  script, which caused my test class to error.   I have fixed the CaseTestTrigger Class but I am still only get ting 76% code coverage.  The issue now is I have not been able to write the appropriate script to CaseTestTrigger to test two area in the CaseCommentValidate Trigger. 

The two problem areas  that  casetesttrigger are not touching are documented below. I am getting closer thanks to you Anupam.  Still working on test class.  I will let you know if I am able to increase my code coverage to at least 80% LOL!.  Have an Awesome Day! 

trigger CaseCommentValidate on CaseComment (before delete, before update) {
       Id profileId=userinfo.getProfileId();
    String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
    system.debug('ProfileName'+profileName);
      
     if (Trigger.isDelete) {
          for (CaseComment caseComment : Trigger.old) {
             Case parentCase = [Select Id, Lucity_Parks__c, Lucity_Public_Works__c, Lucity_Returned_Date__c from Case where Id =:caseComment.parentId];
             if((parentCase.Lucity_Public_Works__c== TRUE || parentCase.Lucity_Parks__c == TRUE) && parentCase.Lucity_Returned_Date__c == null && profileName != 'System Administrator')  {
                 caseComment.addError('Comments cannot be deleted on cases being integrated with Lucity'); -Problem Area 1
             }      
          }
     }
     else   {
           for (CaseComment caseComment : Trigger.new) {
               CaseComment oldCaseComment  = Trigger.oldMap.get(caseComment.ID);
               Case parentCase = [Select status , Id, Lucity_Parks__c, Lucity_Public_Works__c, Lucity_Returned_Date__c from Case where Id =:caseComment.parentId];
               if((parentCase.Lucity_Public_Works__c== TRUE || parentCase.Lucity_Parks__c == TRUE) && parentCase.Lucity_Returned_Date__c == null && profileName != 'System Administrator')  {
                   if(caseComment.CommentBody != oldCaseComment.CommentBody)
                      caseComment.addError('Comments cannot be changed on cases being integrated with Lucity');  --Problem Area 2
               }      
            }
     }          
}
Salesforce Admin2Salesforce Admin2
Hi Anupam, I know you haven't heard from me in a while.  I have good new and bad news.  Good news first.  I have two triggers to test, so I wrote two different methods in my CaseTestTriggerFrances class.  The good news Test method t2 I was able to get 100 % code coverage but in my test method t1 I am only getting 76%.  How can I test the profilename from my CaseCommentValidate trigger?  The profilename is not a field on the case record or comments record.  My test script does not get best that line of code the contains the profilename != 'System Administrator'.  Any suggestion would be much appreciated.  Thank You.

.@isTest
public class CaseTestTriggersFrances {

   static testmethod void t1() {
  
  
   //When a new case (First Case) is created
        case cs = new case();
        cs.Subject= 'Testing';
        cs.Origin='Phone';
        cs.Description = 'FL Testing Triggers calls';
        cs.Status ='Open';
        cs.Lucity_Public_Works_valid__c='yes';
        cs.Location_Format__c='Street Address';
        cs.Street_Name__c='LINCOLN ST';
        cs.Street_Number__c='230';
        cs.Send_Case_Creation_Email_to_Contact__c=False;
        cs.Lucity_Returned_Date__c=null;
       
        insert cs;
       
        casecomment ccom = new casecomment ();
        ccom.commentBody = cs.Description;
        ccom.parentid = cs.id;
        insert ccom;
        try {
            ccom.CommentBody = 'Changed the Description 1';
            update ccom;
            Delete ccom;
        }
        catch (Exception e) {
           
            Boolean exceptionThrown = e.getMessage().contains('Comments cannot be changed on cases being integrated with ...')? true : false;
            System.assertEquals(exceptionThrown, true);
        }

       // try {
       //     delete ccom;
      //  }
     //   catch (Exception e) {
           
      //      Boolean exceptionThrown = e.getMessage().contains('Comments cannot be deleted on cases being integrated with ...')? true : false;
     //       System.assertEquals(exceptionThrown, true);
      //  }       

        case cs2 = new case();
        cs2.Subject= 'Testing';
        cs2.Origin='Phone';
        cs2.Description = 'FL Testing Triggers calls';
        cs2.Status ='New';
        cs2.Lucity_Public_Works_valid__c='yes';
        cs2.Location_Format__c='Street Address';
        cs2.Street_Name__c='LINCOLN ST';
        cs2.Street_Number__c='230';
        cs2.Send_Case_Creation_Email_to_Contact__c=False;
        cs2.Lucity_Returned_Date__c=null;
       
        insert cs2;
     
        casecomment ccom2 = new casecomment ();
        ccom2.commentBody = cs2.Description;
        ccom2.parentid = cs2.id;
        insert ccom2;

      try{
          ccom2.CommentBody = 'new test2';          
          update ccom2;           
          delete ccom2;
          }
          catch(Exception ex)    {
          System.assert(ex.getMessage().contains('Comments cannot be deleted on cases being integrated with Lucity'),
          ex.getMessage() );
           }   
          finally    {
              InsertCaseCommentInLucity iCom = new InsertCaseCommentInLucity();
              //  iCom.callCommentFuture(c.Lucity_WR_ID__c ,c.Id,true,cm.CommentBody);
              //  iCom.callCommentFuture(c.Lucity_WR_ID__c ,c.Id,false,null);
            }    
           
           
}      
     
       //t2 method test the LucityValidate trigger         
      static testmethod void t2() {
       Case c = new Case(
                             Subject='testCase',
                             Service_Request_Type__c = 'SW New Container Request',
                             Description = 'FL Testing Triggers calls',
                             Recycling_Container_QTY__c=4,
                             Refuse_Container_QTY__c=4,
                             Customer_Type__c='Business',New_Container_Issue__c='First Container',
                             Payment_Most_Likely_Needed__c=TRUE,
                             Payment_Method__c='Pay in Person',
                             status='New',
                             Street_Number__c='230',
                             Street_Name__c='Lincoln st',                            
                             Lucity_Public_Works_valid__c='yes'                       
                             );
            insert c;    

    
 
      Case cas = new Case(
                     Subject='testCase',
                     Service_Request_Type__c = 'Alarms:  City Offices',
                     Lucity_User1_Type_Main__c ='Alarms: City Offices',
                     Lucity_Public_Works_Valid__c='yes',
                     status='New',Street_Number__c='230',
                     Street_Name__c='Lincoln st',
                     Description='Change Comments Test');
      insert cas;
      
      cas.parentId=c.id;
      cas.Lucity_WR_ID__c = '99999';
      cas.Lucity_Returned_Date__c=null;        
      update cas;
      
    
      cas.status=null;
      cas.Lucity_WR_ID__c = null;

       Try{
           update cas;
           }      
       Catch(Exception ex){
           //Assert Error Message
            System.assert(ex.getMessage().contains('New cases being integrated with Lucity must have a Status = New'),
                ex.getMessage() );
       }
      
      Try{
           delete cas;
           }      
       Catch(Exception ex){
           //Assert Error Message
            System.assert(ex.getMessage().contains('Cases being integrated with Lucity cannot be deleted'),
                ex.getMessage() );
       }   
      
       } 
   
}
Anupam RastogiAnupam Rastogi
Hi,

Is it that you are not logged in as System Administrator when you are running the Test Class? If yes then you need to use runAsmethod so that the code is executed using a System Administrator profile to achieve 100% code coverage.

Add the following bold lines within the t1 method as shown later.
 
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 

User u = new User(Alias = 'standt', Email='standarduser@abcorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='testtempu3083@torg.com'); 

System.runAs(u) {

//--- Existing t1 method code to be added

}

So your entire test class should look like - 
@isTest
public class CaseTestTriggersFrances {

   static testmethod void t1() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
		User u = new User(Alias = 'standt', Email='standarduser@abcorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='testtempu3083@torg.com');
        
        System.runAs(u) {

            //--- Add the existing code of method t1 into these curly brackets. This will run the current t1 code as System Admin and provide 100% coverage

        }
    }


   static testmethod void t2() { 

      ...............

      ...............

      ...............
   }

}

Thanks
AR

If you found the reply useful that solved your problem then please mark it as best answer.
 
Salesforce Admin2Salesforce Admin2
Hi Anupam
the issue is that I am a system administrator that is testing the script but my issue is in order to test  the if statement that states not equal to 'System Administrator'. 
In other words I need to test script for a non-System Administrator user.  So I did try to use  your code in the following way but it gave me a " System.QueryException: List has no rows for assignment to SObject".  p.S I modified it some what to incorporate one of our license's users.  Thanks Anupam for  all you assistance in help. 
profileName != 'System Administrator'
@isTest
public class CaseTestTriggersFrances {
 
   static testmethod void t1()  {
    
   Profile profileName = [SELECT Id,Name FROM Profile WHERE Name='Supervisors'];
   User u = new User(Alias = 'mhicks', Email='mhicks@hampton.gov', EmailEncodingKey='UTF-8', LastName='Hicks',
   LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = profileName.Id, TimeZoneSidKey='America/New_York', UserName='mhicks@hampton.gov.staging');
 
   System.runAs(u)
  // system.debug('ProfileName'+profileName)


  }
           
}      
 
Anupam RastogiAnupam Rastogi
Hi,

What it the line of code which is throwing this error?

Meanwhile, guessing it myself, I think you either mentioned a profile name ('Supervisors') wrongly as it does not exists or it is misspelt.

Check the screen shot of the same class that I have which is giving 100% code coverage. I would recommend you to use the standard user profile instead for a test run, making sure the spelling is correct.

User-added image

Thanks
AR

If you find the reply useful which solves your problem then please mark it as best answer.
Salesforce Admin2Salesforce Admin2
Hi Anupam, sorry I didn't follow your original instructions, of course you are right:-).  When I used the standard user my test classt did passed. Unfortunately I am still  getting only 76% code coverage (see image 1 below).   I needed to figure out how to change the user because the if statements does check this too.  Thank you so much for helping me with that.    I provided a screen below to show the area I can't get pass (highlighted in red).  User-added image
User-added image
Anupam RastogiAnupam Rastogi
I am not able to understand your problem here. This is a different Trigger which I guess is currently tested by the method t2.
Salesforce Admin2Salesforce Admin2
Hi Anupam  sorry for the cofusion  it is the same trigger the  trigger name just changed you know it as  CaseCommentValidate trigger the actual name is LucityCaseCommentValidate trigger the code has not change.  Thanks
Salesforce Admin2Salesforce Admin2
Hi Again Anupam what I was attempting to show you  was a visual image of the  code coverage of the CaseCommentValidate trigger , which is the name you know it as when executing the  CaseTestTriggersFrances  class in the Development console.   I hope I have cleared up some of the confusion.  You have help me so much. I am new to apex code so you are dealing with a person that have a lot of hurdles to cross LOL! No worries you have taught and share some much knowledge.with me.  It has help me a lot.  Thank You so much!
Salesforce Admin2Salesforce Admin2
Stopping discussion here Anupam,  I don't want you use any more of your valuable time with me.   I think I just need to rework my logic in my test class a l ittle to get pass the if statements in the trigger.  Now that you gotten me passed the user profile piece (standard user), I think I am good to go. Thanks Again Anupam ! 
Anupam RastogiAnupam Rastogi
To avoid confusions, share the entire Trigger and the Test Class codes again. I guess you have two Triggers and one test class for testing both of them. And for that I would recommend you to have separate test classes.

Anyways, share the code for all of them - Triggers and Test Classes. And for doing so use the <> button on the palette above, as it presents the code in readable format.

Thanks
AR
Salesforce Admin2Salesforce Admin2
Ok. Thank you again for your support and assistance!☺ Frances
Anupam RastogiAnupam Rastogi
Its okay if you share the code.
Salesforce Admin2Salesforce Admin2
Hi Anupam I did finally reach100% code coverage on my trigger test classes we discussed previous. I have posted another issues on the forum title: I need help in improving code coverage test class for batchsync class. I am only receiving 31% code coverage for following batch class (batchsyn) and i do not understand how to write test code that tests the API requests.   I did get one response that pointed me to the  https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_http_testing_httpcalloutmock.htm site.  Put I am at a loss right now on how to properly implement the httpcalloutmock class.  I did not send you any apex code because I have already posted it on this forum by the title above.  Any assistance you can give me would be much appreciated.  Thanks