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
AkiTAkiT 

Batch Apex - testing problem

 global class BatchMerger implements Database.Batchable<SObject>{

  private final String query; global BatchMerger(String q){query = q;} global database.querylocator start(Database.BatchableContext BC){return Database.getQueryLocator(query);} global void execute(Database.BatchableContext BC, Sobject[] scope){ Map <Id, Account> dupes = new Map <Id, Account>(); for(sobject s : scope){ Account a = (Account)s; dupes.put(a.Id, a); } // Look for dupes Contacts List <Contact> contacts = new List <Contact>(); for(Contact c : [select Id, AccountId from Contact where AccountId in :dupes.keySet()]){ c.AccountId = dupes.get(c.AccountId).Real_Acct__c; contacts.add(c); } // updates Database.Saveresult[] src=Database.update(contacts); } global void finish(Database.BatchableContext BC){ } }

 

I have above simple batch to reparent account contacts. It works ok, but in the testing I am not able to get assertions to succeed.

 

 

TEST DATA CREATIONS...

 

...

String query = 'select Id, Real_Acct__c, dupe__c ' +'from Account ' +'where Real_Acct__c != null ' +'and dupe__c = true ' +'limit 200'; BatchMerger cln = new BatchMerger(query); Id batchProcessId = Database.executeBatch(cln); Test.StopTest(); AsyncApexJob[] jobs = [select TotalJobItems, Status, Id from AsyncApexJob where Id = :batchProcessId]; system.assertEquals(1, jobs[0].TotalJobItems); <-- THIS IS OK! system.assertEquals(0, [select count() from Opportunity where AccountId = :dupes[0].Id]); <-- THIS FAILS, actual being 1 - the one opp in that in test data was assigned to this account dupes[0].

 

 Can anyone see what's wrong here ?

 

Thanks for help!