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
Zach CarterZach Carter 

Is there a way to assert the number of times a method is invoked?

Hello all,

 

I was wondering if there was any way inside of a test method, to assert the number of times a method is invoked or in this specific case, the number of times an object was updated.

 

I have a trigger which is responsible for updating an sObject, but only under certain conditions.

 

Besides asserting that the field has not been initialized, is there some way of ensuring that the sobject was not updated during the test / determining how many times the update method was called on the object?

 

If not, this would be a very nice feature for the apex language to have.

 

Thank you,

 

-Zach

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

As far as within native functionality, there isn't. But, you could wire up that class to have a static member that counts it's usage, which you can then examine. Like this:

 

public class xyz {
  static map< id, integer > ctr;
  static {
    ctr = new map< id, integer >( );
  }
  public void dosomething( sobject record ) {
    if( !ctr.containskey( record.id ) ) {
      ctr.put( record.id, 0 );
    }
    ctr.put( record.id, ctr.get( record.id ) + 1 );
    // do rest of logic here
  }
  @isTest
  public static integer recordCount( id recordid ) {
    return ctr.get( record.id ) == null ? 0 : ctr.get( record.id );
  }
}

 

All Answers

sfdcfoxsfdcfox

As far as within native functionality, there isn't. But, you could wire up that class to have a static member that counts it's usage, which you can then examine. Like this:

 

public class xyz {
  static map< id, integer > ctr;
  static {
    ctr = new map< id, integer >( );
  }
  public void dosomething( sobject record ) {
    if( !ctr.containskey( record.id ) ) {
      ctr.put( record.id, 0 );
    }
    ctr.put( record.id, ctr.get( record.id ) + 1 );
    // do rest of logic here
  }
  @isTest
  public static integer recordCount( id recordid ) {
    return ctr.get( record.id ) == null ? 0 : ctr.get( record.id );
  }
}

 

This was selected as the best answer
Zach CarterZach Carter

Thanks fox,

 

I thought about doing something like this but I'm not sure whether or not the rest of my team would approve.

 

Hopefully SF will at some point focus on improving the features of unit tests in Apex.