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
RarLopzRarLopz 

Test Class Batch Class


global class DuplicateContactMergeBatch implements Database.Batchable<sObject> {

	global Database.QueryLocator start(Database.BatchableContext bc){
       // collect the batches of records or objects to be passed to execute. 
       // DuplicateRecordSet is a list of Contacts (Duplicate RecordItems) idenified as Duplicates by the Duplicate Rule
    	
		string conduplicateruleid;
		list<DuplicateRulesId__c> cs = [select id, ContactDuplicateRuleId__c from DuplicateRulesId__c limit 1];
		if(cs!=null && cs.size() > 0 ){
			for(DuplicateRulesId__c custsetting: cs){
				
			   conduplicateruleid = custsetting.ContactDuplicateRuleId__c;
				system.debug('++++++++++++++++++    ' +conduplicateruleid);
			 }
		}

		// Fetch Id and Name of the Duplicate Record Set 

		return Database.getQueryLocator([
                SELECT id, name 
                FROM DuplicateRecordSet
                Where DuplicateRuleId = :conduplicateruleid 
            ]);  
		
    }
	
	global void execute(Database.BatchableContext BC, List<DuplicateRecordSet> scope) {
              
       //call MergeContacts method to process each batch of records
        MergeContacts(scope); 
        
    }

	public static void  MergeContacts(List<DuplicateRecordSet> dupset){
	
		//iterate through each DuplicateRecordSet, and create a map of duplicaterecordset<Id, DuplicateRecordSet> 
		Map<Id, DuplicateRecordSet> mapDuplicateRecordSet =  new Map<Id,DuplicateRecordSet>();

		if(dupset!=null && dupset.size()>0){
			for(DuplicateRecordSet drs : dupset){
				mapDuplicateRecordSet.put(drs.Id, drs);
			}
		}
		system.debug('map of duplicate record set' +mapDuplicateRecordSet);
		Map<Id, Set<Id>> mapDuplicateRecordItem =  new Map<Id, Set<Id>>();
		for(DuplicateRecordItem drI : [SELECT Id,RecordId, DuplicateRecordSetId 
									   FROM DuplicateRecordItem 
									   where DuplicateRecordSetId IN :mapDuplicateRecordSet.keyset()]){
					
					System.debug('Duplicate record Items: ' +drI);
					if(drI!=null && !mapDuplicateRecordItem.containskey(drI.DuplicateRecordSetId)){
						mapDuplicateRecordItem.put(drI.DuplicateRecordSetId, new Set<Id>{drI.RecordId}); 
					}
					else{
						mapDuplicateRecordItem.get(drI.DuplicateRecordSetId).add(drI.RecordId); 
					}
		} 

		// create a list of contacts that need to be merged 
		list<id> lstContactId = new list<id>(); 
		Set<Id>  setContactId = new set<id>();
		list<contact> mastercontact = new list<contact>();

		// iterate through all DuplicateRecordSet records that has child records 
		for(DuplicateRecordSet dr : [SELECT Id 
									 FROM DuplicateRecordSet 
									 where Id IN : mapDuplicateRecordItem.keyset()]){
			
			// Collect all disctinct contacts from the duplicaterecorditems
			setContactId =  mapDuplicateRecordItem.get(dr.Id);
			system.debug('The elements in the setofid are :' +setContactId.size());
			system.debug('Each of these elements is :' +setContactId);                             
										 
		}

		for(Contact con : [SELECT Id, lastname,email, ownerid,phone 
							   FROM Contact 
							   WHERE Id In : setContactId 
							   order by CreatedDate DESC LIMIT 1]){		
													   
							   IF(con!=null){
								mastercontact.add(con);
							   }
							   setContactId.remove(con.Id);  
							   lstContactId.addAll(setContactId);  
		}

		system.debug('master contact ' +mastercontact[0]);
		system.debug('new elemensts in the setContactId' +setContactId);
		system.debug('list of dupicated contacts ' +lstContactId);

		if(mastercontact.size()>0 && mastercontact!=null){
			try{
				Database.merge (mastercontact[0],lstContactId, true);
			}	catch (DmlException e) {
				// Process exception
				System.debug('An unexpected error has occurred: ' + e.getMessage()); 
			} 
		}
	
	}

	global void finish(Database.BatchableContext bc){
       // execute any post-processing operations
    }   

}

@isTest 
public class DuplicateContactMergeBatchTest{

    public static testMethod void testContactMerge() {
        
       	// Create a test user        	
       	User oUser = TestDataHelper.createUser('Lender', 'Testra1', 'testra1@emailtest.com', 'Dealer Sales Representative', true);
       	
       	// Create test dealer Accounts
       	Account oAccount1 = TestDataHelper.createAccount('Testonera Account-1', 'Dealer Account', 'RAA-1', oUser.Id, false);
       	Account oAccount2 = TestDataHelper.createAccount('Testtwora Account-2', 'Dealer Account', 'RAA-2', oUser.Id, false);
        
        List<Account> accounts = new List<Account>{oAccount1,oAccount2};
        
        insert accounts;
                
        System.assertEquals( 1, [ SELECT count() FROM Account WHERE id = :oAccount1.id ] );
        System.assertEquals( 1, [ SELECT count() FROM Account WHERE id = :oAccount2.id ] );
        
        //Create a Dealer Contact record
        Contact oContact1 = TestDataHelper.createContact(oAccount1.Id, 'TestConOne', 'TestLastname', 'Dealer Contact', '9995551212', oUser.Id, true);
        
        Contact oContact2 = oContact1.clone(); 
        
        insert oContact2;
        
        System.assertEquals( 1, [ SELECT count() FROM Contact WHERE id = :oContact1.id ] );
        System.assertEquals( 1, [ SELECT count() FROM Contact WHERE id = :oContact2.id ] );
        
        list<Contact> contacts = new list<Contact>();
        contacts.add(oContact1);
        contacts.add(oContact2);
        
        system.debug('The contactlistsize is ' +contacts.size() );
        
        // if no duplicate record sets have been created yet
        // then let's manually insert them so we can test the merge
        Integer dupeCount = [ SELECT count() FROM DuplicateRecordItem WHERE recordId IN :contacts ];
        system.debug('Thiiiiiii ' +dupeCount);
        if ( dupeCount == 0 ) {
            insertDuplicateRecordSet( contacts );
        }
        
        Test.startTest();
            DuplicateContactMergeSched sh1 = new DuplicateContactMergeSched();
            String sch = '0 0 23 * * ?';
            system.schedule('Test DuplicateContactMergeSched', sch, sh1);
        Test.stopTest();
        
    }
    
     private static void insertDuplicateRecordSet( List<Contact> contacts ) {
     
        //Database.DMLOptions insertDML = new Database.DMLOptions(); 
        //insertDML.DuplicateRuleHeader.AllowSave = true; 
        
        DuplicateRule rule = [ SELECT id FROM DuplicateRule 
                                WHERE DeveloperName = 'Standard_Rule_for_Contacts_with_Duplicate_Contacts' LIMIT 1 ];
                                
                                system.debug('RULLLLLLLLLeeee ' +rule.id);
                                
        //Database.SaveResult[] sr = Database.insert(contacts, insertDML);        
        DuplicateRecordSet drs = new DuplicateRecordSet(
            duplicateRuleId = rule.id
        );
        
        insert drs;
        
        system.debug('>>>>>>>>>>>>' +drs);

        List<DuplicateRecordItem> items = new List<DuplicateRecordItem>();
        
        for ( Contact cnt : contacts ) {
            items.add( new DuplicateRecordItem(
                duplicateRecordSetId = drs.id,
                recordId = cnt.id
            ));
        }
        
        insert items;
        
    }
    
}


 
global class DuplicateContactMergeSched implements Schedulable{
   global void execute(SchedulableContext SC) {
    DuplicateContactMergeBatch b = new DuplicateContactMergeBatch(); 
    database.executebatch(b);      
    }
}
Code covergae is only 17%. The entire execute method (highlighted in bold is not covered). 
Any suggestions?
Best Answer chosen by RarLopz
Raj VakatiRaj Vakati
Got it what is casuing an issue .. 


You need to insert the ContactDuplicateRuleId__c  custom setting value in test class like an object 

All Answers

Raj VakatiRaj Vakati
Make sure you have duplicate rules active .. can u check the test class is running successfully or not .. give me an error is its failing 
RarLopzRarLopz
@RajVakatai 

The DuplicateRule is active. Test Class is not failing. 
It doesn't cover any lines in the execute method i.e lines 27 to line 101
Raj VakatiRaj Vakati
Got it what is casuing an issue .. 


You need to insert the ContactDuplicateRuleId__c  custom setting value in test class like an object 
This was selected as the best answer
RarLopzRarLopz
that was it !  its 97% now. 

I created a record for custom setting in the test class. 
 
// Create a custom setting record
    	    	
DuplicateRulesId__c csobj = new DuplicateRulesId__c ();
csobj.ContactDuplicateRuleId__c = [SELECT id 
                                                          FROM DuplicateRule 
                                                          WHERE DeveloperName = 
                                     'Standard_Rule_for_Contacts_with_Duplicate_Contacts' LIMIT 1].id;
				
insert csobj;

@RajVakati , Can you please guide me on what / how I can improve my code in the future. ? 
Raj VakatiRaj Vakati
sure .. ping me on rajamohanvakati@gmail.com .. 

Close this thread 

https://developer.salesforce.com/forums/ForumsMain?id=9062I000000QvWwQAK
prati puriprati puri
global class ConActualLastModifiedDateBatch implements Database.Batchable<sObject>{
    //Id batchJobId = Database.executeBatch(new ConActualLastModifiedDateBatch(), 100);
    // AND RecordCount <=3
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator([
            SELECT Id, Name 
            FROM DuplicateRecordSet
            WHERE DuplicateRuleId = '0Bm1T0000006RWISA2' AND RecordCount > 1
            /*SELECT Id, Name 
            FROM DuplicateRecordSet WHERE Id = '0GK5600000097OuGAI'*/
        ]);
    }
    global void execute(Database.BatchableContext BC, List<DuplicateRecordSet> scope) {
        Set<String> duplicateRecordIdSet = new Set<String>();
        for(DuplicateRecordSet drs : scope){
            duplicateRecordIdSet.add(drs.Id);
        }
        List<DuplicateRecordItem> duplicateRecItemList = 
            [
                SELECT Id,RecordId, DuplicateRecordSetId
                FROM DuplicateRecordItem
                WHERE DuplicateRecordSetId IN :scope
            ];
        List<Contact> updateConList = new List<Contact>();
        Set<String> conRecIdSet = new Set<String>();
        if(!duplicateRecItemList.isEmpty()){
            for(DuplicateRecordItem duplicateRecItem : duplicateRecItemList){
                if(String.valueOf(duplicateRecItem.RecordId).startsWithIgnoreCase('003')){
                    conRecIdSet.add(duplicateRecItem.RecordId);                         
                }                
            }
            for(Contact conRec : [SELECT Id, Actual_Last_Modified_Date__c, LastModifiedDate FROM Contact WHERE Id IN:conRecIdSet]){
                conRec.Actual_Last_Modified_Date__c = conRec.LastModifiedDate;
                updateConList.add(conRec);
            }
        }
        if(!updateConList.isEmpty()){
            update updateConList;
        }
    }
    global void finish(Database.BatchableContext BC){
        Database.executeBatch(new ConFixWhomMasterBatch(), 1);
    }
}
Can anyone help me with Test class