0

I have a batch class that implements Database.Stateful and it is filling a Map collection at the execute method alongside other things. This map is then utilized to send emails related to the records within it at the finish method. To ensure that the heap size limit is not exceeded, I've implemented logic within the execute method. This logic checks the heap size / sends emails and clears the Map if the limit has reached or exceeded 90% without waiting the finish method. However, I'm uncertain about how to effectively test this logic in my test class. Could someone guide me on how to approach testing this heap size control logic within the execute method? Your insights are greatly appreciated. Thank you.

 public void execute(Database.BatchableContext ctx, List<sObject> scope) {
     if(Limits.getHeapSize() > (0.90 * Limits.getLimitHeapSize())) {
          Send all EmailMessage instances in unit of work collection;
          Clear the Map and unit of work collections;
     }

     other logic;
 }

1 Answer 1

1

You want to use dependency injection

Create a static property in the batchable

@TestVisible heapLimit {
  get {
    if (heapLimit == null) {heapLimit = Limits.getLimitHeapSize());}
    return heapLimit;
  } set;
}

And, in your code, change this line:

if(Limits.getHeapSize() > (0.90 * Limits.getLimitHeapSize())) {

to:

if(Limits.getHeapSize() > (0.90 * heapLimit)) {

Then, in your testmethod

 MyBatchable.heapLimit = 1000;

So, at run time, you've injected a lower heap limit that allows for testing.

3
  • Thank you very much! Simple yet effective. I appreciate it.
    – selman
    Mar 7 at 19:20
  • the same technique can be used for dependency injecting today's date, the now time, etc.
    – cropredy
    Mar 7 at 21:32
  • Yay! I grasped the logic very well. Thank you once again.
    – selman
    Mar 7 at 22:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .