I have a scenario where a trigger should take certain actions based on the number of Contacts assigned to an Account: If a Contact has no account assigned it will look for a special "Unassigned" Account and assign this to the contact. But if an Account has a large number of Contacts already it should not be used.
To test this I need to create an account that has more than the limit of Contacts (in my case its 5000)
I've tried to create a simple batch class to support this:
public class BulkInsert implements Database.Batchable<sObject>{
public List<sObject> objects;
public BulkInsert ( List<sObject> objs){
this.objects = objs;
}
public Iterable<sObject> start(Database.BatchableContext BC){
return objects;
}
public void execute(Database.BatchableContext BC, List<sObject> scope){
insert scope;
}
public void finish(Database.BatchableContext BC){
}
}
This is used in the test as follows:
account = new Account(Name='Unassigned');
insert account;
bucket_o_contacts = new List<Contact>();
for (Integer i = 0; i < 5000; i++){
c = new Contact(LastName='Contact' + i, Account=account);
bucket_o_contacts.add(c);
}
Test.startTest();
Database.executeBatch(new BulkInsert(bucket_o_contacts));
Test.stopTest();
Why doesn't this work? Have I misunderstood how Batchable works?
This is the error I get:
System.UnexpectedException: No more than one executeBatch can be called from within a testmethod. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.
If I write some Anonymous Apex and execute it then the batch works:
Contact c;
Account account = new Account(Name='Unassigned');
insert account;
List<Contact> bucket_o_contacts = new List<Contact>();
for (Integer i = 0; i < 500; i++){
c = new Contact(LastName='Contact' + i, Account=account);
bucket_o_contacts.add(c);
}
Database.executeBatch(new BulkInsert(bucket_o_contacts));
Any ideas?