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
Michael Hedrick 2Michael Hedrick 2 

Update contact owner to account owner test class coverage

Hello All,
I have a Batch Class where I am updating all of the Contact Owners to Match the Account owners.
I am unable to cober the condition in Class.
Here are the Classes.
@isTest

private class TestBatchContactownerUpdate 
{
    static List<Account> aList;
    static testMethod void myUnitTest() 
   
    {
        UpdateContactOwnerToAccountOwnerBatch bat = new UpdateContactOwnerToAccountOwnerBatch();
     
        bat.finish(null);
    }
    static testMethod void testSchedulable()
    {
        Test.startTest();        
        String cron = '0 0 0 17 11 ? 2033';
        System.schedule('BATR99zz', cron, new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
    }
  
    {
     Account acc = new Account(
            Name = 'testaccount'
            ,BillingPostalCode='22821'      
            ,RecordTypeId = '222222' 
        );
        insert acc; 

      
        Account sacc= [SELECT Id, Name,OwnerID from Account Where name = 'testAccount' limit 1];
       
        Contact con = new Contact(
            AccountId = sacc.id
            ,Lastname = 'testcontact'
            ,Firstname ='testdude'
            ,RecordTypeId = '1111111'
        );
        insert con;


       
        Test.startTest();
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
            User u1= new User(Alias = 'standt', Email='testemail@junkmail.com', 
                        EmailEncodingKey='UTF-8', LastName='Tester', LanguageLocaleKey='en_US', 
                        LocaleSidKey='en_US', ProfileId = p.Id, 
                        TimeZoneSidKey='America/Los_Angeles', UserName='testemail@junkmail.com');
            
            System.runAs(u1) {
      // The following code runs as user 'u'  
       // create test contact
        Contact c1 = new Contact(FirstName='Jane',LastName='Doe', Account=acc);
        insert c1;
        
        //assert your results using system.assert and system.asserEquals

        //reload objects to make sure values are loaded
        c1 = [select id, name,  OwnerId from contact where id=:con.id];
        con = [select id, name, OwnerId from contact where id=:con.id];

        acc= [select id, ownerId from Account where id=:acc.id];
       // system.assert(c1.OwnerID = acc.OwnerID);
            
            
            
        Test.stopTest();
        }
    }
}
global class UpdateContactOwnerToAccountOwnerBatch implements Database.Batchable<sObject>, Schedulable{

        
    List<contact> contactsToChangeOwner = new List<contact>();
    global final String Query ='SELECT Id, AccountId, Ownerid, Account.ownerid from contact where AccountId != null';
       global Database.QueryLocator start(Database.BatchableContext BC){
          return Database.getQueryLocator(query);
       }
       
       global void execute(Database.BatchableContext BC, List<contact> scope){
        
        for(contact con: scope){     ----  No Coverage
            if(con.ownerid!=con.Account.ownerid){    ----  No Coverage
                con.ownerid = con.Account.ownerid;     ----  No Coverage
                contactsToChangeOwner.add(con);    ----  No Coverage
            }           
        }
        update contactsToChangeOwner;      ----  No Coverage
       }
       
    global void finish(Database.BatchableContext BC){}
    
    global void execute(SchedulableContext sc)
    {
      Database.executeBatch(new UpdateContactOwnerToAccountOwnerBatch ());
    } 
    
    
    
}

If someone would review my Test Class it would be greatly appreciated.
Cheers,
M
 
Best Answer chosen by Michael Hedrick 2
Maharajan CMaharajan C
Ok Micheal try to separate the transaction of setup and not-setup objects dml like below:


@isTest
public class TestBatchContactownerUpdate {
    static testmethod void testBatchAccountOwnerReassignment(){
        
        Profile p = [SELECT Id FROM profile 
                     WHERE name='System Administrator']; 
        
        User accUser = new User(alias = 'newUser1', 
                                email='accuser@testorg.com', 
                                emailencodingkey='UTF-8', lastname='Testing', 
                                languagelocalekey='en_US', 
                                localesidkey='en_US', profileid = p.Id, 
                                timezonesidkey='America/Los_Angeles', 
                                username='accuser@testorg.com');
        User conUser = new User(alias = 'newUser2', 
                                email='conuser@testorg.com', 
                                emailencodingkey='UTF-8', lastname='Testing', 
                                languagelocalekey='en_US', 
                                localesidkey='en_US', profileid = p.Id, 
                                timezonesidkey='America/Los_Angeles', 
                                username='conuser@testorg.com');
        insert accUser;
        insert conUser;
        
        system.runAs(accUser)
        {
        List<Account> accs = new List<Account>();
        for(integer i = 0; i < 200; i++){
            accs.add(new Account(name = 'test', 
                                 ownerId = accUser.id));
        }
        insert accs;
        
        List<Contact> cons = new List<Contact>();
        for(integer i = 0; i < 200; i++){
            cons.add(new Contact(lastname = 'test'+i, Email='test'+i+'@testorg.com',
                                 ownerId = conUser.id,AccountId = accs[i].Id));
        }
        insert cons;
        
        Test.startTest();
        Database.executeBatch(new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
        }
    }
    
    static testMethod void testSchedulable()
    {
        Test.startTest();        
        String cron = '0 0 0 17 11 ? 2033';
        System.schedule('BATR99zz', cron, new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
    }
    
}

Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Micheal,

Please try the below test class:

@isTest
public class TestBatchContactownerUpdate {
    static testmethod void testBatchAccountOwnerReassignment(){
        
        Profile p = [SELECT Id FROM profile 
                     WHERE name='System Administrator']; 
        
        User accUser = new User(alias = 'newUser1', 
                                email='accuser@testorg.com', 
                                emailencodingkey='UTF-8', lastname='Testing', 
                                languagelocalekey='en_US', 
                                localesidkey='en_US', profileid = p.Id, 
                                timezonesidkey='America/Los_Angeles', 
                                username='accuser@testorg.com');
        User conUser = new User(alias = 'newUser2', 
                                email='conuser@testorg.com', 
                                emailencodingkey='UTF-8', lastname='Testing', 
                                languagelocalekey='en_US', 
                                localesidkey='en_US', profileid = p.Id, 
                                timezonesidkey='America/Los_Angeles', 
                                username='conuser@testorg.com');
        insert accUser;
        insert conUser;
        
        
        List<Account> accs = new List<Account>();
        for(integer i = 0; i < 200; i++){
            accs.add(new Account(name = 'test', 
                                 ownerId = accUser.id));
        }
        insert accs;
        
        List<Contact> cons = new List<Contact>();
        for(integer i = 0; i < 200; i++){
            cons.add(new Contact(lastname = 'test'+i, Email='test'+i+'@testorg.com',
                                 ownerId = conUser.id,AccountId = accs[i].Id));
        }
        insert cons;
        
        Test.startTest();
        Database.executeBatch(new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
    }
    
    static testMethod void testSchedulable()
    {
        Test.startTest();        
        String cron = '0 0 0 17 11 ? 2033';
        System.schedule('BATR99zz', cron, new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
    }
    
}

Thanks,
Maharajan.C
Michael Hedrick 2Michael Hedrick 2
Thank you for the reply Maharajan,
The testBatchAccountOwnerReassignment method have an error. 
System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Account, original object: PermissionSetAssignment: []
Class.TestBatchContactownerUpdate.testBatchAccountOwnerReassignment: line 31, column 1

 
Maharajan CMaharajan C
Ok Micheal try to separate the transaction of setup and not-setup objects dml like below:


@isTest
public class TestBatchContactownerUpdate {
    static testmethod void testBatchAccountOwnerReassignment(){
        
        Profile p = [SELECT Id FROM profile 
                     WHERE name='System Administrator']; 
        
        User accUser = new User(alias = 'newUser1', 
                                email='accuser@testorg.com', 
                                emailencodingkey='UTF-8', lastname='Testing', 
                                languagelocalekey='en_US', 
                                localesidkey='en_US', profileid = p.Id, 
                                timezonesidkey='America/Los_Angeles', 
                                username='accuser@testorg.com');
        User conUser = new User(alias = 'newUser2', 
                                email='conuser@testorg.com', 
                                emailencodingkey='UTF-8', lastname='Testing', 
                                languagelocalekey='en_US', 
                                localesidkey='en_US', profileid = p.Id, 
                                timezonesidkey='America/Los_Angeles', 
                                username='conuser@testorg.com');
        insert accUser;
        insert conUser;
        
        system.runAs(accUser)
        {
        List<Account> accs = new List<Account>();
        for(integer i = 0; i < 200; i++){
            accs.add(new Account(name = 'test', 
                                 ownerId = accUser.id));
        }
        insert accs;
        
        List<Contact> cons = new List<Contact>();
        for(integer i = 0; i < 200; i++){
            cons.add(new Contact(lastname = 'test'+i, Email='test'+i+'@testorg.com',
                                 ownerId = conUser.id,AccountId = accs[i].Id));
        }
        insert cons;
        
        Test.startTest();
        Database.executeBatch(new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
        }
    }
    
    static testMethod void testSchedulable()
    {
        Test.startTest();        
        String cron = '0 0 0 17 11 ? 2033';
        System.schedule('BATR99zz', cron, new UpdateContactOwnerToAccountOwnerBatch());
        Test.stopTest();
    }
    
}

Thanks,
Maharajan.C
This was selected as the best answer
Michael Hedrick 2Michael Hedrick 2
Perfect.  I actually had to turn my Account Process Builder off becuase I was getting a CPU time out error but 100% coverage.
Thank you Maharajan.