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
Swapna PrasadeSwapna Prasade 

in apex test how to assert if a method in apex class is getting called and how many times

In Apex Test , i need to verify that specific method of the Apex class that i am testing, is getting called when i run the test. I am looking for something similar to .toHaveBeenCalledTimes () that is available in javascript.

Appreciate any help on this!
Best Answer chosen by Swapna Prasade
Shubham Jain 338Shubham Jain 338
Hi Swapna,

There is no method that tells you a method runs how many times. You can create a global static variable and every time when the method runs in that method increment the variable and at last, in the test class, you will get the count in the variable.

Please mark this as the best answer if it helps.

Thanks
Shubham Jain

All Answers

Shubham Jain 338Shubham Jain 338
Hi Swapna,

There is no method that tells you a method runs how many times. You can create a global static variable and every time when the method runs in that method increment the variable and at last, in the test class, you will get the count in the variable.

Please mark this as the best answer if it helps.

Thanks
Shubham Jain
This was selected as the best answer
Swapna PrasadeSwapna Prasade
Thanks Shubham, this is great suggestion! I will try this!
Shubham Jain 338Shubham Jain 338
Hi Swapna,

If it works for you, please mark it as the best answer, it would really help.

Thanks
Shubham Jain
Swapna PrasadeSwapna Prasade
Sure I will! Wanted to ask how do I declare global variable? Can I use public static variable instead and refer to it as Classname.variable name in the test class to validate the counter?
Shubham Jain 338Shubham Jain 338
Hi,

Yes, you can. Declare a variable public static Integer counter = 0; in the apex class.

Thanks
Shubham Jain
Swapna PrasadeSwapna Prasade
Thanks! This helps!