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
Rajendra Prasad 44Rajendra Prasad 44 

i am getting error when deploying test class to production, but not failing in sandbox

accont trigger handler:
public with sharing class AccountTriggerHandler extends TriggerHandler {
    /**
    * @Description : 
    1. Calls queuable class to set the request with the matched accounts
    2. Calls DocuSignUtil class when account stage is "Application" and Stage is "05 - Polocy Issued"
    */
    protected override void onAfterUpdate() {
        if (!isTriggerActive()) return; 
        System.enqueueJob(new AccountPartnerSyncQueueable(getElegranMatchingAccounts(Trigger.New),'Elegran','PUSH'));
        
        // send attachment if RecordType is "Application", account stage is changed to '05-polocy issued'
        List<Account> docuSignAccounts = getDocuSignMatchingAccounts(Trigger.New, Trigger.oldMap);
            if (!docuSignAccounts.isEmpty()) {
                 DocuSignUtil.sendAttachment(docuSignAccounts);
            }
    }
    
     /**
    * check Trigger_Settings__mdt to see if the Active__c flag is set for this trigger
    * @return   true if active else return false
    */
    
    private  static Boolean isTriggerActive() {
        
        List<TriggerSetting__mdt> triggerMute = new List<TriggerSetting__mdt>();
        triggerMute = [Select DeveloperName,MasterLabel,Active__c,TriggerName__c from TriggerSetting__mdt WHERE DeveloperName = 'Account_Sync_Elegran' AND TriggerName__c = 'AccountTrigger' Limit 1];          
        if(triggerMute.size()>0 ){
            return  triggerMute[0].Active__c;
        }else{
            return true;
        }  
    }
    
    /**
    * @Description : Calls queuable class to set the request with the matched accounts
    * @param1 : accounts will be the Trigger.new records
    * @return : returns the matched accounts that meets the conditions.
    */
    public static Boolean ranElegranIntegration = false;    
    private List<Account> getElegranMatchingAccounts(List<Account> accounts){
        
        List<Account> accs = new List<Account>();
        if(ranElegranIntegration == false){
            ranElegranIntegration = true;
            Set<Id> tenant1Ids = new Set<Id>();
            for(Account acc: accounts) {
                tenant1Ids.add(acc.Tenant_1__c);
            }
            List<Contact> tenant1List = [SELECT Id,FirstName,LastName,Risk_Class__c,Desired_Rent_Amount__c,Description FROM Contact where Id IN: tenant1Ids];
            Map<Id,Contact> accVsTenant1Map = new Map<Id,Contact>();
            
            for(Account acc:accounts) {
                if(acc.Tenant_1__c !=null) {
                    for(Contact con: tenant1List) {
                        accVsTenant1Map.put(acc.Id,con);
                    }
                }
            }
            
            for(Account acc: accounts){
                if((accVsTenant1Map.keySet().contains(acc.Id) && accVsTenant1Map.get(acc.Id).Risk_Class__c == null) && acc.What_state_are_you_looking_to_live_in__c == 'NY' && ((acc.Gross_Monthly_Rent__c != null && acc.Gross_Monthly_Rent__c >= 2500) || (accVsTenant1Map.keySet().contains(acc.Id) && accVsTenant1Map.get(acc.Id).Desired_Rent_Amount__c != null && accVsTenant1Map.get(acc.Id).Desired_Rent_Amount__c >= 2500) )) {
                    accs.add(acc);
                }
            }
        }
        
        return [SELECT Id,Name,Tenant_1__c,Tenant_1__r.Email,Tenant_1__r.Phone,Tenant_1__r.FirstName,Tenant_1__r.LastName,
                Gross_Monthly_Rent__c,Tenant_1__r.Desired_Rent_Amount__c,Tenant_1__r.Description FROM Account Where Id IN: accs and Tenant_1__c != null];
    }
    
    /**
    * @Description : To Filter The Accounts to Send DocuSign Attachments To Accounts Related Apartment_Building Email Adress
    * @param1 : accounts will be the Trigger.new records
    * @Param2 : oldAccountById be the Trigger.oldMap
    * @return : returns the matched accounts that meets the conditions.
    */
    private list<account> getDocuSignMatchingAccounts(list<account> accounts, map<id,sObject> oldAccountsMap){
        Map<Id, account> oldAccountById =  (Map<Id, account>) oldAccountsMap;
        list<account> filteredAccounts = new list<account>();
        // get Record type to filter the accounts
        Map<ID,Schema.RecordTypeInfo> rt_Map = Account.sObjectType.getDescribe().getRecordTypeInfosById();
        
        for(account acc : accounts){
            boolean recordType = rt_Map.get(acc.recordTypeID).getName().containsIgnoreCase('Application');
            if( recordType && acc.Stage__c != oldAccountById.get(acc.id).Stage__c  && acc.Stage__c == '05 - Policy Issued'){ 
                filteredAccounts.add(acc);
            }
        }
        return filteredAccounts;
    }
}
DocuSignUtil
public class DocuSignUtil {
    /** 
    @ this class will be called when the account record type = 'application' and stage = '05 - polocy issued' 
    @ if so then sends the attachment of 'docusign status' to the 'land lord' of current account.
    */
    
    public static void sendAttachment( list<account> acclist){

        set<id> AccIds = (new map<id, account> (acclist)).keySet();
        /**
        * Query To get Latest record of docusign based on docusign status( dsfs__Envelope_Status__c ) related to Accounts
         @Docusign relationship name = R00N80000002eb1GEAQ__r
        */
        list<account> accountDocuSignsList = [ select id,name,(select id,dsfs__Envelope_Status__c from R00N80000002eb1GEAQ__r
                                                               where dsfs__Envelope_Status__c = 'completed' 
                                                               ORDER BY lastmodifieddate DESC limit 1) from account where id IN : AccIds ];
        
        
        /** 
*  creating map of Docusign id, related account
*/
        map<id,id> AccIdByDocId = new map<id,id>();
        for(account a: accountDocuSignsList){
            for(dsfs__DocuSign_Status__c docSign : a.R00N80000002eb1GEAQ__r){
                AccIdByDocId.put(docSign.id,a.Id);
            }
        }
        
        /**
        @ Map of content document Id(attachment id), key('docusign status' obj id) of related account id 
        */
        map<id,id> LinkedEntityIdByContentDocumentId = new map<id,id>();
        
        /**
         * Map of Id(LinkedEntityId) , values(set of ContentDocumentId's related to LinkedEntityId)
         */
        map<id,set<id>> ContentDocumentIdByLinkedEntityId = new map<id,set<id>>();
        
        for(ContentDocumentLink DocLink : [select id,LinkedEntityId,ContentDocumentId from ContentDocumentLink 
                                           where LinkedEntityId IN : AccIdByDocId.keyset()]){
                                               LinkedEntityIdByContentDocumentId.put(DocLink.ContentDocumentId, DocLink.LinkedEntityId);
                                               
                                               if(ContentDocumentIdByLinkedEntityId.containsKey(DocLink.LinkedEntityId)){
                                                   ContentDocumentIdByLinkedEntityId.get(DocLink.LinkedEntityId).add(DocLink.ContentDocumentId);
                                               }else{
                                                   ContentDocumentIdByLinkedEntityId.put(DocLink.LinkedEntityId, new set<id>{DocLink.ContentDocumentId});                                               
                                               }
                                           }
        /**
        Map of Account ids and Docusign attachment body
        */                                  
        Map<id,id> AttachmentByAccId = new Map<id,id>();
        for(id Key: ContentDocumentIdByLinkedEntityId.keySet()){
            for(ContentVersion DocBody : [ SELECT id,title,VersionData,ContentDocumentId FROM ContentVersion WHERE ContentDocumentId 
                                          IN : ContentDocumentIdByLinkedEntityId.get(key)
                                          AND ( (title LIKE : '%Tenant%' AND title LIKE :'%Partiicpation%' 
                                                 AND title LIKE :'%Agreement%') OR (NOT title LIKE  : 'certificate%'))
                                          ORDER BY ContentModifiedDate Desc LIMIT 1]) {                                             
                                              id AccId = AccIdByDocId.get(LinkedEntityIdByContentDocumentId.get(DocBody.ContentDocumentId));
                                              AttachmentByAccId.put(AccId, DocBody.Id);
                                }
                      }
        /** 
        * Send email with docuSign Attachement to related Accounts 'Apartment building' Email Address
        */
       if(AttachmentByAccId.values() != NULL){
            list<Messaging.SingleEmailMessage> mailList = new list<Messaging.SingleEmailMessage>();
            emailTemplate EmailTemplt = [select id, name from EmailTemplate where name = 'Policy Issued Landlord Notification New'];
                for(Account account : [select Id,Name,OwnerId,Apartment_Building__r.Email_Address__c from Account where Id IN :AccIds])
                {
                    if(EmailTemplt != null){
                        Messaging.singleEmailMessage mail = Messaging.renderStoredEmailTemplate(EmailTemplt.Id, NULL, account.Id);
                        mail.setToAddresses(new string[] {account.Apartment_Building__r.Email_Address__c});
                        mail.setEntityAttachments(new string[] {AttachmentByAccId.get(account.id)});
                        if(!test.isRunningTest()){
                         mail.setBccAddresses(new string[] {'rajendra@accelerize360.com'}); 
                        }
                        mailList.add(mail);
                    }
                }
            if(mailList.size() > 0){
                Messaging.SendEmailResult[] Result = Messaging.sendEmail(mailList);
            }
        }
    }
}



DocuSignUtilTest:
/**
 * Test Class For "DocuSignUtil" Class(which will be fired by After Trigger when the Account Stage Is Changed to "05 - Polocy Issued" 
 * and record type is "Application")
 */
@IsTest(seeAllData = false)
private with sharing class DocuSignUtilTest {
     
    @testSetup private static void testdata(){
        DocuSignTestDataFactory.testData(5);
    }
    
    /**
     * Testing All Possible cases by providing required data
     */
    @isTest private static void UpdateAccount_To_Test_Sending_Email_Attachments(){        
        list<account> accUpdatList = [select id,name from account where name LIKE : '%testing trigger%'];
        
        Test.startTest();
        Integer invocations;
        try{
            DocuSignUtil.sendAttachment(accUpdatList);
            invocations = Limits.getEmailInvocations();
        } catch (Exception e) {
             invocations = Limits.getEmailInvocations();
        }
        Test.stopTest();
      system.assertNotEquals(0, invocations, 'An email should be sent');
    }
    
    /**
     * test if content version record title is not matched
     */
    @isTest private static void UpdateAccount_To_Test_Whether_Attachments_Filtered_Even_If_Attachment_Title_Not_matched(){
        list<ContentVersion> ContentVersionList = new list<ContentVersion>();
        for(ContentVersion Doc: [SELECT id,Title from ContentVersion]){
            Doc.Title = 'certificate';
            ContentVersionList.add(Doc);
        }
        update ContentVersionList;
         list<account> accUpdatList = [select id,name from account where name LIKE : '%testing trigger%'];
        Test.startTest();
            Integer invocations;
            try{
                DocuSignUtil.sendAttachment(accUpdatList);
                invocations = Limits.getEmailInvocations();
            } catch (Exception e) {
                 invocations = Limits.getEmailInvocations();
            }
        Test.stopTest();

        system.assertEquals(0, invocations, 'An email should not be sent');
        }
        /**
         * testing Whether Email can be sent or not without Documents
         */
        @isTest private static void UpdateAccount_To_Test_Whether_Email_Send_Even_If_There_Are_No_Documents_Available_For_Docusign_Related_To_Account(){
          delete [SELECT id from ContentDocument];
          list<account> accUpdatList = [select id,name from account where name LIKE : '%testing trigger%'];
         Test.startTest();
            Integer invocations;
            try{
                DocuSignUtil.sendAttachment(accUpdatList);
                invocations = Limits.getEmailInvocations();
            } catch (Exception e) {
                 invocations = Limits.getEmailInvocations();
            }
        Test.stopTest();
        system.assertEquals(0, invocations, 'An email should not be sent');
         }
    
        /**
         * testing if Accounts related record -"Apartment_Building" record Email is null
         */
        @isTest private static void UpdateAccount_To_Test_Email_Being_Sent_Even_If_Recipient_Email_Is_Null(){
          account a = [select id,name,Email_Address__c from account where name LIKE : '%new apartment%'];
            a.Email_Address__c = '';
            update a;
         list<account> accUpdatList = [select id,name from account where name LIKE : '%testing trigger%'];
        Test.startTest();
            Integer invocations;
            try{
                DocuSignUtil.sendAttachment(accUpdatList);
                invocations = Limits.getEmailInvocations();
            } catch (Exception e) {
                 invocations = Limits.getEmailInvocations();
            }
        Test.stopTest();    
        system.assertEquals(0, invocations, 'An email should not be sent');
      }
}

AcountTriggerTest:
/*
* @Description - This test class is to provide test data for AccountTrigger & AccountTriggerHandler
* This Test class Also Tests The Trigger Logic On After Update To sent Attachments To Related Account
*  When Stage is '05 - Polocy Issued' And Aplication Type is 'Application'.
*/
@isTest(seeAllData = false)
private class AccountTriggerTest {
     @testSetup private static void testdata(){
        DocuSignTestDataFactory.testData(2);
    }
  
    private static testMethod void getMatchingAccounts_TriggerHandlerTest(){
        
        List<Contact> conList = new List<Contact>();
        List<Account> accList = new List<Account>();
        
        for(Integer i=0; i<=10; i++) {
            Contact con = new Contact(LastName = 'Application'+i, FirstName='Tenant 01', Phone='9999999999',Email='testemail@email.com',Desired_Rent_Amount__c=3000,Description='Description For Contact');
            conList.add(con);
        }
        insert conList;
        
        for(Contact con: conList) {
            Account acc = new Account(Name = con.LastName, Tenant_1__c = con.Id,Gross_Monthly_Rent__c=2500,What_state_are_you_looking_to_live_in__c='NY');
            accList.add(acc);
        }
        insert accList;
        
        List<TriggerSetting__mdt> ts = [Select DeveloperName,MasterLabel,Active__c,TriggerName__c from TriggerSetting__mdt WHERE DeveloperName = 'Account_Sync_Elegran' AND TriggerName__c = 'AccountTrigger'];
      
        Test.startTest();
        update accList;
        if ( ts.isEmpty() || ts[0].Active__c == true) {
            System.AssertNotEquals(1,Limits.getQueueableJobs());
        }else if(ts[0].Active__c == false){
            System.AssertEquals(0,Limits.getQueueableJobs());
        }
        Test.stopTest(); 
    }
  /**
   * Testing Email Sending Functionality When The Stage Is Changed To '05 - Policy Issued'.
   */    
    @isTest private static void updateAccount_withChangedStage_toSendDocuSignAttachment(){
       list<account> accUpdatList = new list<account>();
         for(account aa : [select id,name,Stage__c from account where name LIKE : '%testing trigger%' LIMIT 1]){
                aa.Stage__c = '05 - Policy Issued';
                accUpdatList.add(aa);
            }
        Test.startTest();
        Integer invocations;
        try{
             update accUpdatList;
             invocations = Limits.getEmailInvocations();
        } catch (exception e){
            invocations = Limits.getEmailInvocations();
        }
        
        Test.stopTest();
        
     system.assertEquals(1, invocations, 'An email should be sent');
    }
}

DocusignTestDataFactory:
/**
 * @Description: Provides Test data for DocuSignUtilTest Test Class
 * @Objects : Account, dsfs__DocuSign_Status__c, ContentVersion, ContentDocumentLink
 */
@isTest(seeAllData = false)
public class DocuSignTestDataFactory {
   public static void testData(integer recordsCount) {
        id applicationRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Application').getRecordTypeId();
        id AppartmentbuildingRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Building').getRecordTypeId();
        
         // sample account(apartments building record) of recordType "Building"
        account appartmentBuildingAcc = new account(name='new apartment',RecordTypeId = AppartmentbuildingRecordTypeId,
                                 Email_Address__c='rajendraprasadmalla7396@gmail.com');
        insert appartmentBuildingAcc;
        
        // sample account records
        list<account> accList = new list<account>();
        
        for(integer i=0; i < recordsCount; i++){
            account acc = new account();
            acc.Name = 'testing Trigger'+i;
            acc.RecordTypeId = applicationRecordTypeId;
            acc.Stage__c = '04 - Agreement Signed';
            acc.Apartment_Building__c = AppartmentBuildingAcc.id;
            accList.add(acc);
        }
        insert accList;
                
         // sample Docusign status record related to Account record
         list<dsfs__DocuSign_Status__c> docList = new list<dsfs__DocuSign_Status__c>();
        
        for(integer i=0; i < accList.size(); i++){
            dsfs__DocuSign_Status__c docSign = new dsfs__DocuSign_Status__c();
            docSign.dsfs__Company__c = accList.get(i).Id;
            docSign.dsfs__Envelope_Status__c = 'completed';
            docList.add(docSign);
        }
        insert docList;
        
       // content version record to inserting sample attachments
       list<ContentVersion> contentList = new list<ContentVersion>();
        for(integer i=0; i < accList.size(); i++){
            ContentVersion cv = new ContentVersion();
            cv.Title = i+'Tenant Partiicpation Agreement.pdf';
            cv.PathOnClient = i+'Tenant Partiicpation Agreement.pdf';
            cv.VersionData = Blob.valueOf('Test Content Document');
            cv.IsMajorVersion = true;
            contentList.add(cv);
        }
        Insert contentList;
        
        set<id> contentId = (new map<id,sObject> (contentList)).keyset();

        // Get ContentDocumentsId from Content Version
        list<ContentVersion> conDocId = [SELECT id,ContentDocumentId FROM ContentVersion WHERE Id IN : contentId];
        // ContentDocumentLink To link the Document To DocuSignStatus Record
        list<ContentDocumentLink> docLink = new list<ContentDocumentLink>();
        for(integer i=0; i < accList.size(); i++){
            ContentDocumentLink cd = New ContentDocumentLink();
            cd.LinkedEntityId = docList.get(i).id;
            cd.ContentDocumentId = conDocId.get(i).ContentDocumentId;
            cd.shareType = 'V';
            docLink.add(cd);
        }
        Insert docLink;
    }
}

here it is the error im getting when deploying:
User-added image
 
AnudeepAnudeep (Salesforce Developers) 
You are likely running into an exception in your AcountTriggerTest and the 
update accUpdatList operation might be failing which is causing a failure in assertion. Does your debugs show that accUpdatList is populated and the query 'select id,name,Stage__c from account where name LIKE : '%testing trigger%' LIMIT 1' returns results?
catch (exception e){
            invocations = Limits.getEmailInvocations();
        }
Anudeep
Rajendra Prasad 44Rajendra Prasad 44
in sandbox its working. but when deplloying its failing.