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
RaoSRaoS 

Test Class is failing after changing the Actual class

Hello Gurus,
I had a trigger(generates an email on department name change) and a test class related to this trigger.  The coverage was 100%. I changed the trigger to fire only when the profile is <> System Administrator.  The trigger is working fine as expected but the Test class is failing.  Here is the trigger code and followed by Test class code.
--------------------------------------------------------------
trigger SendEmailAfterDeptCodeUpdate on Department__c (after update) {
Profile p = [ Select Id, Name from Profile where Id =: UserInfo.getProfileId() ];
        if( !p.Name.equalsIgnoreCase( 'System Administrator' ) ) 
        {
  List<Id> lstdeptsToUpdate=new List<Id>(); 
for(Department__c dept : trigger.new)
{
    If (dept.Name !=trigger.oldMap.get(dept.Id).Name)
    {
    lstdeptsToUpdate.add(dept.Id);
    }
}
    
    If(lstdeptsToUpdate.size()>0)
    {
    Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
    
   // string header = '*TR Customer Code, *Customer Name,*TR Department ID,*Original Department Code,*New Department Code,*SubBranchCode,TR Customer Id \n';
 string header = 'SubBranchCode,TRCustomerId,TRDepartmentID,OriginalDepartmentCode,NewDepartmentCode,TRCustomerCode \n';

    string finalstr = header ;
    String Emailbody;
        
    
    string csvname= 'template_to_update_WO_inv_dept.txt';
    csvAttc.setFileName(csvname);
    
    system.debug('header:' + header);
     String messageBody,priorvalue;   
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    //email.setSubject('Department Code change in Salesforce');     
   for (Department__c dep1 : [Select id, Name,Service_Entity__r.Customer_Name__c,TR_Customer_Code__c,trDepartmentID__c,Service_Entity__r.Sub_Branch__c,Service_Entity__r.Sub_Branch__r.Sub_Branch_Code__c,Service_Entity__r.TR_Customer_Id__c from Department__c where id in : lstdeptsToUpdate and Service_Entity__r.Send_To_TR__c=True])
        {
     priorvalue=trigger.oldMap.get(dep1.Id).Name; 
     //string recordString = dep1.TR_Customer_Code__c + ','+ dep1.Service_Entity__r.Customer_Name__c+','+dep1.trDepartmentID__c +','+priorvalue+','+dep1.Name+','+dep1.Service_Entity__r.Sub_Branch__r.Sub_Branch_Code__c +','+dep1.Service_Entity__r.TR_Customer_Id__c +'\n';
     string recordString = dep1.Service_Entity__r.Sub_Branch__r.Sub_Branch_Code__c+','+dep1.Service_Entity__r.TR_Customer_Id__c+','+dep1.trDepartmentID__c +','+priorvalue+','+dep1.Name +','+ dep1.TR_Customer_Code__c  +'\n';

          finalstr = finalstr +recordString;
      
         messageBody = '<html><body>';
         messageBody = messageBody + 'Here are the details for the change in Department Code in Salesforce ';
         messageBody = messageBody + '<br>';
         messageBody = messageBody + '<br>';            
         messageBody = messageBody + 'TR Customer Code: '+ dep1.TR_Customer_Code__c;
         messageBody = messageBody + '<br>';
         messageBody = messageBody + 'TR Department ID: ' + dep1.trDepartmentID__c;
         messageBody = messageBody + '<br>';
               
         messageBody = messageBody + 'Original Department Code: ' + priorvalue;
         messageBody = messageBody + '<br>';
         messageBody = messageBody + 'New Department Code: ' + dep1.Name;
         messageBody = messageBody + '<br>';
         messageBody = messageBody + '<br>';            
         messageBody = messageBody + 'Additional details are available in the attached excel. Please update the Work Order and Invoicing details with the new department code.';
         messageBody = messageBody + '<br>';
         messageBody = messageBody + '<br>';            
         messageBody = messageBody + 'Assign ticket to - Data Management Backend group';
    
         messageBody = messageBody + '</body></html>';       
    
    blob csvBlob = Blob.valueOf(finalstr);    
    csvAttc.setBody(csvBlob);

    system.debug('----');    
    email.setSubject('Department Code change in Salesforce updated to ' + dep1.Name ); 
    email.setHtmlBody(messageBody);

    email.setToAddresses(new String[]{'raos@gmail.com'});
    email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
    system.debug('email...' + email );
    if(email != null)
      {
       Messaging.sendEmail(new Messaging.singleEmailMessage[] {email}); 
       //   system.debug('Inside send email');
      } 
    }        
}
        }
}
--------------------------------------------------------------
@IsTest
public class SendEmailAfterDeptCodeUpdateTest {
static testMethod void SendEmailAfterDeptCodeUpdateTest()
    {
        Profile p = [ Select Id, Name from Profile where name='System Administrator' limit 1 ];
        //Profile p = [ Select Id, Name from Profile where name='Standard Sales User' limit 1 ];
        User standardSales = new User(profileId = p.id, username ='standarduserAdmin@peak.com', email = 'standarduser123@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname123');
        insert standardSales;
        system.runAs(standardSales)
        {   /*Account a=new Account(Name='Test1',BillingCountry='United States',BillingState='Indiana');
            insert a;
         
            Acquisition__c ac= new Acquisition__c(Name='Test Ac');
            insert ac;
         
            Service_Entity__c Se1=new Service_Entity__c(Customer_Name__c='Testa',Legal_Entity__c='Archive Systems Inc.',Account__c=a.id,AcquisitionDB__c=ac.id);
            insert Se1;*/
            
            Department__c dept1= new Department__c(Name='Test Dept',Department_Name__c='Sample Dept',  CurrencyIsoCode='USD',Service_Entity__c='a0t1W00000Un1kR'); //Se1.Id);
            test.startTest();
            insert dept1;
            test.stopTest();
        }


    }
    static testMethod void updateDepartmentTest1(){
                
        Profile p2 = [ Select Id, Name from Profile where name='Onboarding Team' limit 1 ];
        User standardSales2 = new User(profileId = p2.id, username ='standarduserAdmin123@peak.com', email = 'standarduseranc@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname1231');
        insert standardSales2;

       system.runAs(standardSales2)
        {   Department__c dept11= new Department__c(Name='Test Dept123',Department_Name__c='Sample Dept123',  CurrencyIsoCode='USD',Service_Entity__c='a0t1W00000Un1qH'); //Se1.Id);
            insert dept11  ;   
            test.startTest();
            dept11.Name='Test Dept1243';
            Update dept11;
            test.stopTest();
        }   
    }
    static testMethod void updateDepartmentTest(){
        Profile p = [ Select Id, Name from Profile where name='System Administrator' limit 1 ];
        User standardSales = new User(profileId = p.id, username ='standarduserAdmin@peak.com', email = 'standarduser123@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname123');
        insert standardSales;
        system.runAs(standardSales){
            Department__c dept2= new Department__c(Name='Test Dept2',Department_Name__c='Sample Dept2',  CurrencyIsoCode='USD',Service_Entity__c='a0t1W00000Un4UM'); //Se1.Id);
            insert dept2;
            
            test.startTest();
            dept2.Name='Test Dept3';
            Update dept2;
            test.stopTest();
        }
    }
}
--------------------------------------------------------------

I am getting the following error message

System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

Stack trace is showing this message:
Class.SendEmailAfterDeptCodeUpdateTest.updateDepartmentTest1: line 39, column 1

I have highlighted the line 39.  The new method that i have include is updateDepartmentTest1().

Let me know the mistake I am doing.

Thanks
Rao
Best Answer chosen by RaoS
Andrew GAndrew G
IN your trigger i see this line of code
for (Department__c dep1 : [Select id, Name,Service_Entity__r.Customer_Name__c,TR_Customer_Code__c,trDepartmentID__c,Service_Entity__r.Sub_Branch__c,Service_Entity__r.Sub_Branch__r.Sub_Branch_Code__c,Service_Entity__r.TR_Customer_Id__c from Department__c where id in : lstdeptsToUpdate and Service_Entity__r.Send_To_TR__c=True])
short version
[Select id
//and a Bunch of fields 
FROM Department__c 
WHERE id in : lstdeptsToUpdate 
     AND Service_Entity__r.Send_To_TR__c=True])

your test data
Service_Entity__c Se1=new Service_Entity__c(
  Customer_Name__c='Testa',
  Legal_Entity__c='Archive Systems Inc.', 
  Account__c=a.id,
  AcquisitionDB__c=ac.id,
  Delivery_Country__c='United States', 
  Billing_Group__c='Monthly Storage / Monthly Svc')
Does Send_To_TR__c  need to be set in the test record, or is it a computed field in the record?

Regards
Andrew
 

All Answers

Alain CabonAlain Cabon
@Raos

You are using an Id of a custom object very likely: Service_Entity__c='a0t1W00000Un4UM'  without the isTest(SeeAllData=true) Annotation at the beginning of the class.

You need to create a new instance of object for the service entity otherwise.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_seealldata_using.htm

 
String objectName = findObjectNameFromRecordIdPrefix('a0t');
System.debug(objectName);

static String findObjectNameFromRecordIdPrefix(String recordIdOrPrefix){
        String objectName = '';
        try{
            //Get prefix from record ID
            //This assumes that you have passed at least 3 characters
            String myIdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3);
             
            //Get schema information
            Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
             
            //Loop through all the sObject types returned by Schema
            for(Schema.SObjectType stype : gd.values()){
                Schema.DescribeSObjectResult r = stype.getDescribe();
                String prefix = r.getKeyPrefix();
               // System.debug('Prefix is ' + prefix);
                 
                //Check if the prefix matches with requested prefix
                if(prefix!=null && prefix.equals(myIdPrefix)){
                    objectName = r.getName();
                    System.debug('Object Name! ' + objectName);
                    break;
                }
            }
        }catch(Exception e){
            System.debug(e);
        }
        return objectName;
 }

The code above in the anonymous window [CTRL+E] will found the name of the object with the prefix "a0t". 
SabrentSabrent
check the permssion for the profile 'Onboarding Team' 
Seems like this profile doesnt have permissions to Create records for the Department__c object. 
Also as @Alain Cabon has mentioned, avoid using hard coded id's in your code.
Alain CabonAlain Cabon

 Hard coded id's cannot work for a custom object without  the @isTest(SeeAllData=true) Annotation at the beginning of the class.
RaoSRaoS
Thanks @Alain & @Rov.

I have modified test class code to remove the hard coding and getting the record id instead and used it.  I was able to fix the issues. But the coverage is coming only 36%.  The code related to email content is not getting covered.  Here is the updated Test class

@IsTest
public class SendEmailAfterDeptCodeUpdateTest {
static testMethod void SendEmailAfterDeptCodeUpdateTest()
    {
        Profile p = [ Select Id, Name from Profile where name='System Administrator' limit 1 ];
        //Profile p = [ Select Id, Name from Profile where name='Standard Sales User' limit 1 ];
        User standardSales = new User(profileId = p.id, username ='standarduserAdmin@peak.com', email = 'standarduser123@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname123');
        insert standardSales;
        system.runAs(standardSales)
        {   Account a=new Account(Name='Test1',BillingCountry='United States',BillingState='Indiana');
            insert a;
         
            Acquisition__c ac= new Acquisition__c(Name='Test Ac');
            insert ac;
         
            Service_Entity__c Se1=new Service_Entity__c(Customer_Name__c='Testa',Legal_Entity__c='Archive Systems Inc.',Account__c=a.id,AcquisitionDB__c=ac.id,Delivery_Country__c='United States',Billing_Group__c='Monthly Storage / Monthly Svc');
            insert Se1;
                        
            Department__c dept1= new Department__c(Name='Test Dept',Department_Name__c='Sample Dept',  CurrencyIsoCode='USD',Service_Entity__c= Se1.Id);

            //Department__c dept1= new Department__c(Name='Test Dept',Department_Name__c='Sample Dept',  CurrencyIsoCode='USD',Service_Entity__c='a0t1W00000Un1kR'); //Se1.Id);
            test.startTest();
            insert dept1;
            test.stopTest();
        }


    }
    static testMethod void updateDepartmentTest1(){
                
        Profile p2 = [ Select Id, Name from Profile where name='Onboarding Team' limit 1 ];
        User standardSales2 = new User(profileId = p2.id, username ='standarduserAdmin123@peak.com', email = 'standarduseranc@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname1231');
        insert standardSales2;

       system.runAs(standardSales2)
        {   

             Account a1=new Account(Name='Test12',BillingCountry='United States',BillingState='Indiana');
            insert a1;
         
            Acquisition__c ac1= new Acquisition__c(Name='Test Ac1');
            insert ac1;
         
            Service_Entity__c Se12=new Service_Entity__c(Customer_Name__c='Testa12',Legal_Entity__c='Archive Systems Inc.',Account__c=a1.id,AcquisitionDB__c=ac1.id,Delivery_Country__c='United States',Billing_Group__c='Monthly Storage / Monthly Svc');
            insert Se12; 

            Department__c dept11= new Department__c(Name='Test Dept123',Department_Name__c='Sample Dept123',  CurrencyIsoCode='USD',Service_Entity__c=Se12.Id);
          
         insert dept11  ;   
            test.startTest();  
            dept11.Name='Test Dept1243';
            Update dept11;
            test.stopTest();
        }   
    }
    
        static testMethod void updateDepartmentTest2(){
                
        Profile p21 = [ Select Id, Name from Profile where name='Onboarding Team' limit 1 ];
        User standardSales21 = new User(profileId = p21.id, username ='standarduserAdmin1123@peak.com', email = 'standarduseranc@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nur1231', lastname='lastname12311');
        insert standardSales21;

       system.runAs(standardSales21)
        {   

             Account a13=new Account(Name='Test12',BillingCountry='United States',BillingState='Indiana');
            insert a13;
         
            Acquisition__c ac13= new Acquisition__c(Name='Test Ac1');
            insert ac13;
         
            Service_Entity__c Se123=new Service_Entity__c(Customer_Name__c='Testa123',Legal_Entity__c='Archive Systems Inc.',Account__c=a13.id,AcquisitionDB__c=ac13.id,Delivery_Country__c='United States',Billing_Group__c='Monthly Storage / Monthly Svc');
            insert Se123; 

            Department__c dept113= new Department__c(Name='Test Dept123',Department_Name__c='Sample Dept123',  CurrencyIsoCode='USD',Service_Entity__c=Se123.Id);
         test.startTest();   
         insert dept113  ;   
         test.stopTest();   
        }   
    }
    static testMethod void updateDepartmentTest(){
        Profile p = [ Select Id, Name from Profile where name='System Administrator' limit 1 ];
        User standardSales = new User(profileId = p.id, username ='standarduserAdmin@peak.com', email = 'standarduser123@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname123');
        insert standardSales;
        system.runAs(standardSales){
               Account a2=new Account(Name='Test1',BillingCountry='United States',BillingState='Indiana');
            insert a2;
         
            Acquisition__c ac2= new Acquisition__c(Name='Test Ac');
            insert ac2;
         
            Service_Entity__c Se13=new Service_Entity__c(Customer_Name__c='Testa',Legal_Entity__c='Archive Systems Inc.',Account__c=a2.id,AcquisitionDB__c=ac2.id,Delivery_Country__c='United States',Billing_Group__c='Monthly Storage / Monthly Svc');
            insert Se13;
            Department__c dept2= new Department__c(Name='Test Dept2',Department_Name__c='Sample Dept2',  CurrencyIsoCode='USD',Service_Entity__c='a0t1W00000Un4UM'); //Se1.Id);
            insert dept2;
            
            test.startTest();
            dept2.Name='Test Dept3';
            Update dept2;
            test.stopTest();
        }
    }
}

Let me know how to get the email code covered and bring the coverage to 75%.

Thanks in Advance.

Thanks
Rao
Andrew GAndrew G
IN your trigger i see this line of code
for (Department__c dep1 : [Select id, Name,Service_Entity__r.Customer_Name__c,TR_Customer_Code__c,trDepartmentID__c,Service_Entity__r.Sub_Branch__c,Service_Entity__r.Sub_Branch__r.Sub_Branch_Code__c,Service_Entity__r.TR_Customer_Id__c from Department__c where id in : lstdeptsToUpdate and Service_Entity__r.Send_To_TR__c=True])
short version
[Select id
//and a Bunch of fields 
FROM Department__c 
WHERE id in : lstdeptsToUpdate 
     AND Service_Entity__r.Send_To_TR__c=True])

your test data
Service_Entity__c Se1=new Service_Entity__c(
  Customer_Name__c='Testa',
  Legal_Entity__c='Archive Systems Inc.', 
  Account__c=a.id,
  AcquisitionDB__c=ac.id,
  Delivery_Country__c='United States', 
  Billing_Group__c='Monthly Storage / Monthly Svc')
Does Send_To_TR__c  need to be set in the test record, or is it a computed field in the record?

Regards
Andrew
 
This was selected as the best answer
Ravi karlapudiRavi karlapudi
missing the piece of code to update the department name in the test method SendEmailAfterDeptCodeUpdateTest()
RaoSRaoS
Thank you Andrew.  

I have updated my code but still i am not getting the required coverage.

Thanks.
Rao
SabrentSabrent
can you post, which lines are not covered. Also make sure to use the code tag when posting code so as to retain the formating. 
Andrew GAndrew G
Refer to my earlier post and check your test data.
You have added the reference to Send_To_TR__c to line 52 in test method updateDepartmentTest1 but that line of data appears to be commented out.  Your test data line which you are inserting is at line 53 and does not reference the field required.

Regards
Andrew