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
Teyim PilaTeyim Pila 

How do I assert the number of times a method is invoked?

Hello,
I have the following ApexTrigger which I want to test. I want to test that the second line in the last condition (first code snippet) is called depending on the size of the payload List. So, my question is, is there a way to assert the number of times the method, "makeCallout" is invoked? I will highly appreciate any pointers.
TriggerCallout.makeCallout(body, type);
 
trigger CaseTrigger on Case (after insert) {
    private String type = 'Case';
    List<Case> payload = new List<Case>();
    
    // Only Cases whose origin is the web are sent.
    for(Case newCase : Trigger.new){
        if(newCase.Origin == 'Web'){
            payload.add(newCase);
        }
    }
    
    // No need making a request with an empty body.
    if(!payload.isEmpty()){
        String body = System.JSON.serialize(payload);
        TriggerCallout.makeCallout(body, type);
    }
}

Cheers
Tejender Mohan 9Tejender Mohan 9
Hey,

Seems it will be executed only once. 

Thanks
Tejender Mohan
Raj VakatiRaj Vakati
As per your code it is executng only once .. 

 
Teyim PilaTeyim Pila
I know it won't be executed when the payload array is empty and once when the list is not empty. The question is, how do I test these scenarios. I.e. determine programmatically the number of times the method has been called withing my test class.
Tejender Mohan 9Tejender Mohan 9

@Teyim Pila

On your Test Class, Just Create case without 'web' as the origin and then Insert it.

It will execute the trigger and your Callout part will be executed to give you test coverage.
Here, if your callout part is doing any record change like an update on any record or creation of any record then you can put an assert on those record/update or count.

Thanks