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
Sfdc AdminSfdc Admin 

I am not able to increase code coverage from 65% to 75%. Please find my class and test class below

Here is my class:

public with sharing class BusinessUnitTriggerHandler 
{
    public static void checkDuplicate(List<BusinessUnits__c> units, Map<Id, BusinessUnits__c> oldMap, Boolean isInsert ) 
    {
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();

      // Get System Admin profile Id
      Id profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1].Id;
      System.debug('UAC: profileId' + profileId);

      //Get current User Profile ID
      Id userProfileId = UserInfo.getProfileId() ;
    System.debug('UAC: userProfileId' + userProfileId);

    // Iterate over all business records 
        for( BusinessUnits__c bu : units )
        {  
          // When current user Non-Admin OR these fields are updated 
          if(  profileId != userProfileId &&
            ( isInsert || ( !isInsert && ( bu.LineOfBusiness__c != oldMap.get(bu.Id).LineOfBusiness__c || bu.Contact__c != oldMap.get(bu.Id).Contact__c))) ) 
          {
            lineOfBusiness.add(bu.LineOfBusiness__c);
            contactIds.add(bu.Contact__c);
            unitsToProcess.add(bu);
            businessUnitMap.put(bu.LineOfBusiness__c+bu.Contact__c, 0);
          }
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Get existing Business records 
        for( BusinessUnits__c bu : [SELECT Id, LineOfBusiness__c, Contact__c FROM BusinessUnits__c 
                      WHERE Contact__c IN :contactIds AND LineOfBusiness__c IN :lineOfBusiness AND ID NOT IN :units ])
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          businessUnitMap.put( key, (businessUnitMap.get(key)+1) ) ;
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Iterate again over inserted/updated records 
        for( BusinessUnits__c bu : unitsToProcess )
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          // When Already exists then show error
          if( businessUnitMap.containsKey(key) && businessUnitMap.get(key) > 0 ) bu.addError('Sorry. A Business Relationship for this Business Unit already exists for this Contact.');
        }
    }

    public static void changeOwner(List<BusinessUnits__c> units )
    {
        for(BusinessUnits__c bu : units )
        {
            if( bu.Sales_Rep__c != null && bu.OwnerId != bu.Sales_Rep__c  ) bu.OwnerId = bu.Sales_Rep__c ; 
        }
    }

    public static Map<String, BusinessUnitRulesManagement__c> lobAndUserRoleToBusinessUnitCS
    {
        get
        {
            if(lobAndUserRoleToBusinessUnitCS == null )
            {
                lobAndUserRoleToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    lobAndUserRoleToBusinessUnitCS.put( cs.LineofBusiness__c + '' + cs.RoleDeveloperName__c, cs);
                }
            }
            //for(String key : lobAndUserRoleToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobAndUserRoleToBusinessUnitCS.get(key) );
            return lobAndUserRoleToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    updateContactFromCS()
    *   @Purpose:   When BusinessUnit is Updated then update SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static Boolean RUN_ONCE_UCFCS = true ; 
    public static void updateContactFromCS(List<BusinessUnits__c> units, Map<Id,BusinessUnits__c> oldMap, Boolean isInsert )
    {
        System.debug('UAC: BU updateContactFromCS START ' );
        Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
        Map<Id,Contact> existingContacts = new Map<Id,Contact>();
        Set<Id> contactIdsAddedForUpdate = new Set<Id>();
        List<Contact> contactsToUpdate = new List<Contact>();
        Set<Id> contactIds = new Set<Id>();
        Set<Id> userIds = new Set<Id>();
        Map<Id, String> userIdToUserRole = new Map<Id, String>();

        for(BusinessUnits__c bu : units)
        {
            BusinessUnits__c old =  !isInsert ? oldMap.get(bu.Id) : NULL ; 
            if( isInsert || ( !isInsert && (bu.Sales_Rep__c != old.Sales_Rep__c || bu.Escrow_Officer__c != old.Escrow_Officer__c)) ) 
            {
                if(bu.Sales_Rep__c != null ) userIds.add(bu.Sales_Rep__c);
                if(bu.Escrow_Officer__c != null && bu.Sales_Rep__c != bu.Escrow_Officer__c ) userIds.add(bu.Escrow_Officer__c);
                businessUnitToContactId.put(bu, bu.Contact__c);
                contactIds.add(bu.Contact__c);
            }
        }
        System.debug('UAC: businessUnitToContactId ' + businessUnitToContactId );

        for(User u : [SELECT Id, UserRole.DeveloperName FROM User WHERE ID IN :userIds ])
        {
            userIdToUserRole.put(u.Id, u.UserRole.DeveloperName );
        }
        System.debug('UAC: userIdToUserRole ' + userIdToUserRole );
        
        for(Contact con : Database.query( 'SELECT ' + getFields('Contact') + ' FROM Contact WHERE ID IN :contactIds ') )
        {
            existingContacts.put(con.Id, con);
        }

        for(BusinessUnits__c bu : businessUnitToContactId.keyset() )
        {
            String validUserRole = 
                //ContactTriggerHandler.currentUserRole == 'Administration' && 
                userIdToUserRole.containsKey(bu.Sales_Rep__c) ? userIdToUserRole.get(bu.Sales_Rep__c) : ContactTriggerHandler.currentUserRole ;

            // When no custom setting found for current User Role then Go Back
            if(!lobAndUserRoleToBusinessUnitCS.containsKey(bu.LineOfBusiness__c + '' + validUserRole)) continue ; 

            // Get Custom setting record
            BusinessUnitRulesManagement__c cs = lobAndUserRoleToBusinessUnitCS.get(bu.LineOfBusiness__c + '' + validUserRole);
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 
            
            // Get related Contact 
            Contact con = existingContacts.get(businessUnitToContactId.get(bu));

            // When SalesRep or EscrowOfficer changed 
            if((bu.Sales_Rep__c != con.get(cs.SalesRepFieldonContactAPIName__c) || bu.Escrow_Officer__c != con.get(cs.EscrowOfficerFieldonContactAPIName__c) ) 
                    && !contactIdsAddedForUpdate.contains(con.Id) )
            {
                contactIdsAddedForUpdate.add(con.Id);
                Contact newContact = new Contact();
                newContact.Id = con.Id;
                System.debug('UAC: bu.Sales_Rep__c ' + bu.Sales_Rep__c );
                System.debug('UAC: bu.Escrow_Officer__c ' + bu.Escrow_Officer__c );
                if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) newContact.put(cs.SalesRepFieldonContactAPIName__c, bu.Sales_Rep__c);
                if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) newContact.put(cs.EscrowOfficerFieldonContactAPIName__c, bu.Escrow_Officer__c);
                contactsToUpdate.add(newContact);
            } 
        }

        System.debug('UAC: contactsToUpdate ' + contactsToUpdate );

        // Update Contacts 
        if(contactsToUpdate.size() > 0 ) 
        {
            ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = false ;
            update contactsToUpdate ;
            ContactTriggerHandler.RUN_ONCE_UBUFCS = true ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = true ;
        }

        System.debug('UAC: BU updateContactFromCS END ' );
    
    }

    /**
    *   @Method:    getFields()
    *   @Purpose:   Use to get all fields of passing object  
    *   @Param:     String objName for which you want to get fields
    *   @Return:    Comma seprated fields
    *   @Date:      05/18/2017
    *
    *   @Updates: 
    */
    private static String getFields(String objectName)
    {
        //Broke this out of formatQuery because it could be used separately
        String fields = '';
        
        // Get All Objects List
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        
        // Get object detail which passed as argument
        SObjectType objectType = gd.get(objectName);

        // Get passed object detail
        Schema.DescribeSObjectResult r = objectType.getDescribe();

        //Get all fields for passed object 
        Map<String, Schema.SObjectField> fieldMap = r.fields.getMap();

        // Itterate over all fields and check one by one 
        for (String f: fieldMap.keySet())
        { 
            // Get current field 
            Schema.SObjectField sof = fieldMap.get(f);
            // Get current field detail
            Schema.DescribeFieldResult dfr = sof.getDescribe();

            // when current field is accessible, creatable and defaultonCreare then concatinate in field string
            if( dfr.isAccessible() )
            {
                String fname = dfr.getName(); 
                fields += fname + ', '; 
            }
        }
        
        // remove last comma
        fields = fields.substring(0, fields.length() - 2);
        return fields;
    }


    public static Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS
    {
        get
        {
            if(lobToBusinessUnitCS == null )
            {
                lobToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    if(!lobToBusinessUnitCS.containsKey(cs.LineofBusiness__c)) lobToBusinessUnitCS.put( cs.LineofBusiness__c, cs);
                }
            }
            //for(String key : lobToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobToBusinessUnitCS.get(key) );
            return lobToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    clearValueOnContact()
    *   @Purpose:   When BusinessUnit is Updated then update and clearOut SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static void clearValueOnContact(List<BusinessUnits__c> units)
    {
        System.debug('UAC: BU clearValueOnContact START ' );
     
        
     
        Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();

        // Iterate over BusinessUnit 
        for(BusinessUnits__c bu : units )
        {
            if(bu.Contact__c != null) contactIdToLOB.put(bu.Contact__c, bu.LineOfBusiness__c);
        }
        System.debug('UAC: BU contactIdToLOB ' + contactIdToLOB );
        if(contactIdToLOB.size() == 0) 
           return ; 

        // Get related Contacts 
        contacts = new Map<Id, Contact>( [SELECT Id FROM Contact WHERE ID IN :contactIdToLOB.keyset() ]);

        // Iterate over ContactIds 
        for(Id contactId : contactIdToLOB.keyset() )
        {   
            // Get Custom Setting Business Unit
            BusinessUnitRulesManagement__c cs = lobToBusinessUnitCS.get(contactIdToLOB.get(contactId));
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 

            // Get Contact 
            Contact con = contacts.get(contactId);

            // Clear Out Values on Contact 
            if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) con.put(cs.SalesRepFieldonContactAPIName__c, null);
            if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) con.put(cs.EscrowOfficerFieldonContactAPIName__c, null);
            System.debug('UAC: con ' + con );
        }

        // Update Contact
        ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;
        update contacts.values() ;
        ContactTriggerHandler.RUN_ONCE_UBUFCS = true ; 

        System.debug('UAC: BU clearValueOnContact End ' );
    }

}

Test class:

@isTest
private class BusinessUnitTriggerHandlerTest 
{
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();
      Set<Id> userIds = new Set<Id>();
      Map<Id, String> userIdToUserRole = new Map<Id, String>();
     Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
     Map<Id,Contact> existingContacts = new Map<Id,Contact>();
     Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS;
       Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();
    static testMethod void testCheckDuplicate() 
    {
         
   
        Profile profile = [Select Id from Profile where name = 'ORT Direct Sales User'];
        //UserRole ur = [Select Id from UserRole where UserRole.DeveloperName = 'Central_Direct_Agency'];

        User nonAdminUser = new User( ProfileId = profile.Id, Username = System.now().millisecond() + 'test2@test.com.dev',UserRoleId = '00E1G000000IWzyUAG',
                                    Alias = 'batman', Email='bruce.wayne@wayneenterprises.com', EmailEncodingKey='UTF-8',Firstname='Bruce',
                                    Lastname='Wayne',LanguageLocaleKey='en_US',LocaleSidKey='en_US',TimeZoneSidKey='America/Chicago' );
        System.runAs(new User( Id = UserInfo.getUserId() ))
        {
            Database.insert(nonAdminUser);
        }

        Account acc = TestUtility.createAccount( TestUtility.default_account_rt, false );
        acc.Name = 'sfdcpoint';
        acc.Account_Status__c = 'Active';
        acc.AccountNumber = '001';
        insert acc; 
    
        System.runAs(nonAdminUser)
        {
            Contact cont = TestUtility.createContact( TestUtility.default_contact_rt , acc, false ); 
            cont.MailingStreet = 'Test Street' ;
            cont.MailingCity = 'Minneapolis';
            cont.MailingState = 'MN';
            cont.MailingPostalCode = '55347';
            cont.MailingCountry = 'United States' ; 
            insert cont;
            
            
            BusinessUnitRulesManagement__c cs = new BusinessUnitRulesManagement__c();
            cs.Name = 'AgencyManager';
            cs.EscrowOfficerFieldonContactAPIName__c = 'Text';
            cs.LineofBusiness__c = 'testlob';
            cs.RoleDeveloperName__c = 'uniquetest';
            cs.SalesRepFieldonContactAPIName__c = 'conttext';
            cs.Status__c = 'alltext';
            insert cs;
            Id userId = UserInfo.getUserId() ;
          

            BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
          
            insert bu ; 
  
            try
            {
                BusinessUnits__c bu1 = new BusinessUnits__c( Contact__c = cont.Id,LineOfBusiness__c = 'Western Title Division',Sales_Rep__c = UserId  );
                insert bu1 ;  
            }
            catch(DmlException de )
            {

            } 
  

        }
    

    }
 
Best Answer chosen by Sfdc Admin
Andrew GAndrew G
Hi again.  
If we consider the lack of coveage for clearValueOnContact

In your trigger it is only invoked on delete.  to bypass that criteria you would need a individual call as suggested by Nikhil
Add another test method to your class and try - you will need to flesh it out a little
@IsTest
static void test_clearValueOnContact()
{
	List<BusinessUnits__c> bus = new List<BusinessUnites__c>();
	//create other data - contact/user
	BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
	bus.add(bu);
	insert bus;
	BusinessUnitTriggerHandler.clearValueOnContact(bus);

//now SELECT contacts and assert that the fields are blank.


}
Try that for a start.
I will check back in a short while and give more suggestions.
Regards
Andrew
 

All Answers

Andrew GAndrew G
Hello
That's a fair chuck of code you are asking for help with but it seems incomplete.  I would guess that the trigger is the missing puzzle piece.

Why do I think things are missing?  I can see various methods which aren't being called in the test class. i.e.
  • changeOwner
  • checkDuplicate
  • updateContactFromCS
  • getFields (which is invoked by updateContactFromCS)
  • clearValueOnContact
  • lobToBusinessUnitCS (which is invoked by clearValueOnContact)
And I am assuming that those methods are being called in the Trigger.
(note, some consider best practice that the Trigger contains no Business or code logic other than call the Handler). If you check my answer here you will see what I mean by that trigger structure.
https://developer.salesforce.com/forums/ForumsMain?id=9062I000000IKZFQA4

A few tips for posting:
1. When dumping code, use the "add code sample" button and insert with that - it allows for easier reading of the code.
User-added image
2. When saying you can't achieve coverage, use a tool such as the developer console (or Sublime or Webstorm) to indicate where the coverage is not being achieved.  Or at worst, say what line numbers aren't being covered - assuming you used the "add code sample" button which will number them for you.
User-added image

3.  And if your Trigger has logic in it, then include the Trigger so we get the full picture.  


In the mean time, if you run the tests and then use a tool to view the coverage (e.g. Developer Console) you can get an idea of where the code is not being covered.  Then investigate your code for IF or IF..ELSE statements and set up your test data to ensure it passes into both the IF and the ELSE sections.  And if individual methods aren't being tested, try callng them directly in the Test class.

Regards
Andrew

 
Sfdc AdminSfdc Admin
Hi Andrew,
Thank you for your explaination, I am new to salesforce development and your tips makes lot of sense to me. But I didn't build this class so I am not sure how to increase code coverage.
Find My Trigger below:
**
*   @Date:      08.09.2016
*   @Purpose:   Trigger to check duplicate records
*/
trigger BusinessUnitTrigger on BusinessUnits__c(before insert, before update, after insert, after update, before delete ) 
{
  List<BusinessUnits__c> units = Trigger.isDelete ? Trigger.old : Trigger.new ; 

  if(Trigger.isBefore)
  {
    BusinessUnitTriggerHandler.checkDuplicate(units, Trigger.oldMap, Trigger.isInsert);
    BusinessUnitTriggerHandler.changeOwner(units);  
    if(Trigger.isDelete) BusinessUnitTriggerHandler.clearValueOnContact(units);
  }
  
  if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate ) && BusinessUnitTriggerHandler.RUN_ONCE_UCFCS)
  {
    BusinessUnitTriggerHandler.updateContactFromCS(units, Trigger.oldMap, Trigger.isInsert );
  }
}



Please find my class and Uncovered lines of code below:
**
*   @Date:      08.09.2016
*   @Purpose:   Trigger to check duplicate records
*
*/

public with sharing class BusinessUnitTriggerHandler 
{
    public static void checkDuplicate(List<BusinessUnits__c> units, Map<Id, BusinessUnits__c> oldMap, Boolean isInsert ) 
    {
    	Map<String, Integer> businessUnitMap = new Map<String, Integer>();
    	Set<String> lineOfBusiness = new Set<String>();
    	Set<Id> contactIds = new Set<Id>();
    	List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();

    	// Get System Admin profile Id
    	Id profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1].Id;
    	System.debug('UAC: profileId' + profileId);

    	//Get current User Profile ID
    	Id userProfileId = UserInfo.getProfileId() ;
		System.debug('UAC: userProfileId' + userProfileId);

		// Iterate over all business records 
        for( BusinessUnits__c bu : units )
        {	
        	// When current user Non-Admin OR these fields are updated 
        	if(  profileId != userProfileId &&
        		( isInsert || ( !isInsert && ( bu.LineOfBusiness__c != oldMap.get(bu.Id).LineOfBusiness__c || bu.Contact__c != oldMap.get(bu.Id).Contact__c))) ) 
        	{
        		lineOfBusiness.add(bu.LineOfBusiness__c);
        		contactIds.add(bu.Contact__c);
        		unitsToProcess.add(bu);
        		businessUnitMap.put(bu.LineOfBusiness__c+bu.Contact__c, 0);
        	}
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Get existing Business records 
        for( BusinessUnits__c bu : [SELECT Id, LineOfBusiness__c, Contact__c FROM BusinessUnits__c 
        							WHERE Contact__c IN :contactIds AND LineOfBusiness__c IN :lineOfBusiness AND ID NOT IN :units ])
        {
        	String key = bu.LineOfBusiness__c+bu.Contact__c;
        	businessUnitMap.put( key, (businessUnitMap.get(key)+1) ) ;
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Iterate again over inserted/updated records 
        for( BusinessUnits__c bu : unitsToProcess )
        {
        	String key = bu.LineOfBusiness__c+bu.Contact__c;
        	// When Already exists then show error
        	if( businessUnitMap.containsKey(key) && businessUnitMap.get(key) > 0 ) bu.addError('Sorry. A Business Relationship for this Business Unit already exists for this Contact.');
        }
    }

    public static void changeOwner(List<BusinessUnits__c> units )
    {
        for(BusinessUnits__c bu : units )
        {
            if( bu.Sales_Rep__c != null && bu.OwnerId != bu.Sales_Rep__c  ) bu.OwnerId = bu.Sales_Rep__c ; 
        }
    }

    public static Map<String, BusinessUnitRulesManagement__c> lobAndUserRoleToBusinessUnitCS
    {
        get
        {
            if(lobAndUserRoleToBusinessUnitCS == null )
            {
                lobAndUserRoleToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    lobAndUserRoleToBusinessUnitCS.put( cs.LineofBusiness__c + '' + cs.RoleDeveloperName__c, cs);
                }
            }
            //for(String key : lobAndUserRoleToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobAndUserRoleToBusinessUnitCS.get(key) );
            return lobAndUserRoleToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    updateContactFromCS()
    *   @Purpose:   When BusinessUnit is Updated then update SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static Boolean RUN_ONCE_UCFCS = true ; 
    public static void updateContactFromCS(List<BusinessUnits__c> units, Map<Id,BusinessUnits__c> oldMap, Boolean isInsert )
    {
        System.debug('UAC: BU updateContactFromCS START ' );
        Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
        Map<Id,Contact> existingContacts = new Map<Id,Contact>();
        Set<Id> contactIdsAddedForUpdate = new Set<Id>();
        List<Contact> contactsToUpdate = new List<Contact>();
        Set<Id> contactIds = new Set<Id>();
        Set<Id> userIds = new Set<Id>();
        Map<Id, String> userIdToUserRole = new Map<Id, String>();

        for(BusinessUnits__c bu : units)
        {
            BusinessUnits__c old =  !isInsert ? oldMap.get(bu.Id) : NULL ; 
            if( isInsert || ( !isInsert && (bu.Sales_Rep__c != old.Sales_Rep__c || bu.Escrow_Officer__c != old.Escrow_Officer__c)) ) 
            {
                if(bu.Sales_Rep__c != null ) userIds.add(bu.Sales_Rep__c);
                if(bu.Escrow_Officer__c != null && bu.Sales_Rep__c != bu.Escrow_Officer__c ) userIds.add(bu.Escrow_Officer__c);
                businessUnitToContactId.put(bu, bu.Contact__c);
                contactIds.add(bu.Contact__c);
            }
        }
        System.debug('UAC: businessUnitToContactId ' + businessUnitToContactId );

        for(User u : [SELECT Id, UserRole.DeveloperName FROM User WHERE ID IN :userIds ])
        {
            userIdToUserRole.put(u.Id, u.UserRole.DeveloperName );
        }
        System.debug('UAC: userIdToUserRole ' + userIdToUserRole );
        
        for(Contact con : Database.query( 'SELECT ' + getFields('Contact') + ' FROM Contact WHERE ID IN :contactIds ') )
        {
            existingContacts.put(con.Id, con);
        }

        for(BusinessUnits__c bu : businessUnitToContactId.keyset() )
        {
            String validUserRole = 
                //ContactTriggerHandler.currentUserRole == 'Administration' && 
                userIdToUserRole.containsKey(bu.Sales_Rep__c) ? userIdToUserRole.get(bu.Sales_Rep__c) : ContactTriggerHandler.currentUserRole ;

            // When no custom setting found for current User Role then Go Back
            if(!lobAndUserRoleToBusinessUnitCS.containsKey(bu.LineOfBusiness__c + '' + validUserRole)) continue ; 

            // Get Custom setting record
            BusinessUnitRulesManagement__c cs = lobAndUserRoleToBusinessUnitCS.get(bu.LineOfBusiness__c + '' + validUserRole);
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 
            
            // Get related Contact 
            Contact con = existingContacts.get(businessUnitToContactId.get(bu));

            // When SalesRep or EscrowOfficer changed 
            if((bu.Sales_Rep__c != con.get(cs.SalesRepFieldonContactAPIName__c) || bu.Escrow_Officer__c != con.get(cs.EscrowOfficerFieldonContactAPIName__c) ) 
                    && !contactIdsAddedForUpdate.contains(con.Id) )
            {
                contactIdsAddedForUpdate.add(con.Id);
                Contact newContact = new Contact();
                newContact.Id = con.Id;
                System.debug('UAC: bu.Sales_Rep__c ' + bu.Sales_Rep__c );
                System.debug('UAC: bu.Escrow_Officer__c ' + bu.Escrow_Officer__c );
                if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) newContact.put(cs.SalesRepFieldonContactAPIName__c, bu.Sales_Rep__c);
                if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) newContact.put(cs.EscrowOfficerFieldonContactAPIName__c, bu.Escrow_Officer__c);
                contactsToUpdate.add(newContact);
            } 
        }

        System.debug('UAC: contactsToUpdate ' + contactsToUpdate );

        // Update Contacts 
        if(contactsToUpdate.size() > 0 ) 
        {
            ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = false ;
            update contactsToUpdate ;
            ContactTriggerHandler.RUN_ONCE_UBUFCS = true ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = true ;
        }

        System.debug('UAC: BU updateContactFromCS END ' );
    
    }

    /**
    *   @Method:    getFields()
    *   @Purpose:   Use to get all fields of passing object  
    *   @Param:     String objName for which you want to get fields
    *   @Return:    Comma seprated fields
    *   @Date:      05/18/2017
    *
    *   @Updates: 
    */
    private static String getFields(String objectName)
    {
        //Broke this out of formatQuery because it could be used separately
        String fields = '';
        
        // Get All Objects List
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        
        // Get object detail which passed as argument
        SObjectType objectType = gd.get(objectName);

        // Get passed object detail
        Schema.DescribeSObjectResult r = objectType.getDescribe();

        //Get all fields for passed object 
        Map<String, Schema.SObjectField> fieldMap = r.fields.getMap();

        // Itterate over all fields and check one by one 
        for (String f: fieldMap.keySet())
        { 
            // Get current field 
            Schema.SObjectField sof = fieldMap.get(f);
            // Get current field detail
            Schema.DescribeFieldResult dfr = sof.getDescribe();

            // when current field is accessible, creatable and defaultonCreare then concatinate in field string
            if( dfr.isAccessible() )
            {
                String fname = dfr.getName(); 
                fields += fname + ', '; 
            }
        }
        
        // remove last comma
        fields = fields.substring(0, fields.length() - 2);
        return fields;
    }


    public static Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS
    {
        get
        {
            if(lobToBusinessUnitCS == null )
            {
                lobToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    if(!lobToBusinessUnitCS.containsKey(cs.LineofBusiness__c)) lobToBusinessUnitCS.put( cs.LineofBusiness__c, cs);
                }
            }
            //for(String key : lobToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobToBusinessUnitCS.get(key) );
            return lobToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    clearValueOnContact()
    *   @Purpose:   When BusinessUnit is Updated then update and clearOut SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static void clearValueOnContact(List<BusinessUnits__c> units)
    {
        System.debug('UAC: BU clearValueOnContact START ' );
     
        
     
        Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();

        // Iterate over BusinessUnit 
        for(BusinessUnits__c bu : units )
        {
            if(bu.Contact__c != null) contactIdToLOB.put(bu.Contact__c, bu.LineOfBusiness__c);
        }
        System.debug('UAC: BU contactIdToLOB ' + contactIdToLOB );
        if(contactIdToLOB.size() == 0) 
           return ; 

        // Get related Contacts 
        contacts = new Map<Id, Contact>( [SELECT Id FROM Contact WHERE ID IN :contactIdToLOB.keyset() ]);

        // Iterate over ContactIds 
        for(Id contactId : contactIdToLOB.keyset() )
        {   
            // Get Custom Setting Business Unit
            BusinessUnitRulesManagement__c cs = lobToBusinessUnitCS.get(contactIdToLOB.get(contactId));
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 

            // Get Contact 
            Contact con = contacts.get(contactId);

            // Clear Out Values on Contact 
            if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) con.put(cs.SalesRepFieldonContactAPIName__c, null);
            if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) con.put(cs.EscrowOfficerFieldonContactAPIName__c, null);
            System.debug('UAC: con ' + con );
        }

        // Update Contact
        ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;
        update contacts.values() ;
        ContactTriggerHandler.RUN_ONCE_UBUFCS = true ; 

        System.debug('UAC: BU clearValueOnContact End ' );
    }

}

Uncovered lines of code includes:
1).@Method:    clearValueOnContact() - Complete Method
2).lines 232 to 245
3).lines 144 to 163
4).lines 172 to 176

And Below is my Test class with 65%:

 
@isTest
private class BusinessUnitTriggerHandlerTest 
{
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();
      Set<Id> userIds = new Set<Id>();
      Map<Id, String> userIdToUserRole = new Map<Id, String>();
     Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
     Map<Id,Contact> existingContacts = new Map<Id,Contact>();
     Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS;
       Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();
    static testMethod void testCheckDuplicate() 
    {
         
   
        Profile profile = [Select Id from Profile where name = 'ORT Direct Sales User'];
        //UserRole ur = [Select Id from UserRole where UserRole.DeveloperName = 'Central_Direct_Agency'];

        User nonAdminUser = new User( ProfileId = profile.Id, Username = System.now().millisecond() + 'test2@test.com.dev',UserRoleId = '00E1G000000IWzyUAG',
                                    Alias = 'batman', Email='bruce.wayne@wayneenterprises.com', EmailEncodingKey='UTF-8',Firstname='Bruce',
                                    Lastname='Wayne',LanguageLocaleKey='en_US',LocaleSidKey='en_US',TimeZoneSidKey='America/Chicago' );
        System.runAs(new User( Id = UserInfo.getUserId() ))
        {
            Database.insert(nonAdminUser);
        }

        Account acc = TestUtility.createAccount( TestUtility.default_account_rt, false );
        acc.Name = 'sfdcpoint';
        acc.Account_Status__c = 'Active';
        acc.AccountNumber = '001';
        insert acc; 
    
        System.runAs(nonAdminUser)
        {
            Contact cont = TestUtility.createContact( TestUtility.default_contact_rt , acc, false ); 
            cont.MailingStreet = 'Test Street' ;
            cont.MailingCity = 'Minneapolis';
            cont.MailingState = 'MN';
            cont.MailingPostalCode = '55347';
            cont.MailingCountry = 'United States' ; 
            insert cont;
            
            
            BusinessUnitRulesManagement__c cs = new BusinessUnitRulesManagement__c();
            cs.Name = 'AgencyManager';
            cs.EscrowOfficerFieldonContactAPIName__c = 'Text';
            cs.LineofBusiness__c = 'testlob';
            cs.RoleDeveloperName__c = 'uniquetest';
            cs.SalesRepFieldonContactAPIName__c = 'conttext';
            cs.Status__c = 'alltext';
            insert cs;
            Id userId = UserInfo.getUserId() ;
          

            BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
          
            insert bu ; 
  
            try
            {
                BusinessUnits__c bu1 = new BusinessUnits__c( Contact__c = cont.Id,LineOfBusiness__c = 'Western Title Division',Sales_Rep__c = UserId  );
                insert bu1 ;  
            }
            catch(DmlException de )
            {

            } 
  

        }
    

    }

Thank you for your time to look into this issue.
 
Nikhil SutharNikhil Suthar
Hello,
As you mentioned the remaining code that not yet covered,

Uncovered lines of code includes:
1).@Method:    clearValueOnContact() - Complete Method
2).lines 232 to 245
3).lines 144 to 163
4).lines 172 to 176


You mentioned clearValueOnContact() - Complete Method kindly create and pass List<BusinessUnits__c> units the list in method from test class it will cover remaining code.
Example:
BusinessUnitTriggerHandler. clearValueOnContact(listofBusinessunits);
pass the List<BusinessUnits__c> as argument and your code will be covered for that method. Thanks.


 
Sfdc AdminSfdc Admin
Hello Nikhil,
Thank you for your reply. I tried the method you suggested but I don't see any increase in code coverage. it's still 65%. Any other approach that you would like to suggest.?
Andrew GAndrew G
Hi again.  
If we consider the lack of coveage for clearValueOnContact

In your trigger it is only invoked on delete.  to bypass that criteria you would need a individual call as suggested by Nikhil
Add another test method to your class and try - you will need to flesh it out a little
@IsTest
static void test_clearValueOnContact()
{
	List<BusinessUnits__c> bus = new List<BusinessUnites__c>();
	//create other data - contact/user
	BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
	bus.add(bu);
	insert bus;
	BusinessUnitTriggerHandler.clearValueOnContact(bus);

//now SELECT contacts and assert that the fields are blank.


}
Try that for a start.
I will check back in a short while and give more suggestions.
Regards
Andrew
 
This was selected as the best answer
Andrew GAndrew G
Hi Again
next would be lines 144 onwards - this seems unusual I am assuming that it is failing the
if(cs == null ) continue ;      
test for cs being null, yet the line for 138 does a test which if the Map is empty would throw the continue at that point.
Thought would be to the check the debug logs and see what is reported for the debug line @ 142
 System.debug('UAC: cs ' + cs );
If this is reporting as null, I would check the test data - I get a feeling that cs.RoleDeveloperName__c = 'uniquetest'; in your test data, the string should be equivalent to the DeveloperName of the Role assigned to the user - reference ID 00E1G000000IWzyUAG

(as an aside, I don't like having static Ids in my test code - makes the code less portable)
Consider a SELECT statement to get the Role
UserRole role = [SELECT Id, Name,DeveloperName FROM UserRole WHERE Name = 'myUniqueRoleName'];

Regards
Andrew
 
Sfdc AdminSfdc Admin
Hi Andrew,
Thank you so much, Now testcoverage increased to 82%. Currently I am following your other tipsa and trying to make some changes.
Thanks again for your time.
hunt dutthunt dutt
Nice to see this post here and thanks for that.
 https://peryourhealth.fun
https://liteblue.mobi
ameer khan 24ameer khan 24
amazing:
https://mrameertech.com
safikul khansafikul khan
Hi Andrew,
Thank you so much, Now testcoverage increased to 82%. Currently I am following your other tipsa and trying to make some changes.
Thanks again for your time. hdfriday (https://safikul.in/hdfriday-download-latest-movies/), new year (http://Hi Andrew, Thank you so much, Now testcoverage increased to 82%. Currently I am following your other tipsa and trying to make some changes. Thanks again for your time.)
Nevada WebreNevada Webre
Thank You for giving your time. Myaarpmedicare (http://myaarpmedicare.pro/)
Emma JacksonEmma Jackson

This is a very well written article. I’ll be sure to bookmark it and return to learn more of your helpful information. Thank you for the post. Check this Long Leather Vest (https://www.thegenuineleather.com/category/leather-vest/). I’ll certainly come back.

 
Shana MendezShana Mendez
If you're not gaining coverage for a loop, you need to make sure that your test actually has records to loop over.

Most times, fixing coverage issues comes down to making sure that you create/insert appropriate test data (ideally, in a method with the @testSetup annotation).
For more information visit my webpage term paper help (https://perfectessaywriting.com/term-paper).