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
Kishan Kumar 77Kishan Kumar 77 

I've searched alot on the internet but couldn't find that why do we declare test methods as static? What is the significance?

VinayVinay (Salesforce Developers) 
Hi Kishan,

Test Methods are static because you do not call the test methods explicitly when you run a class for execution. When you run your apex tests these methods needs to be executed whether they are called or not which is why we make them static so they can be run while the class executes.  A static method doesn’t require an instance of the class in order to run. They’re created with every object instantiated from the class in which they’re declared.

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Vinay Kumar
AnudeepAnudeep (Salesforce Developers) 
Hi Kishan -

As per the documentation, Test methods take no arguments and have the following syntax:
 
static testMethod void testName() {
    // code_block
}

If you do not declare a test method as static, you will see the error - 
Error: Compile Error: IsTest methods must be declared as static. It is not specified in the documentation why we need to use static but it is the same reason I believe why static methods are defined in apex classes except for the fact that it is a required parameter in a test class See this documentation to understand why we use static methods

"A static method is used as a utility method, and it never depends on the value of an instance member variable. Because a static method is only associated with a class, it can’t access the instance member variable values of its class."

Let me know if this helps
Andrew GAndrew G
"A static method or variable doesn’t require an instance of the class in order to run."

That would be the key.  Think about how Salesforce wants test methods to run.  They want them to run on demand.  By not requiring an instance of the class they can be invoked directly and you can select the method to run individually of all other methods.

Now, the confusing question, which came first - the chicken or the egg.  Is the individual invoking of classes an intended requirement of Salesforce or is it simply a by-product of the methods being static?

regards
Andrew
Belinda J. DavidsonBelinda J. Davidson
Thanks for this guide. It is really helpful for us and other people:) (https://sportshoesnow.com/best-tennis-shoes-for-standing-all-day/)
zermina khanzermina khan
Thanks everyone for providing this awesome platform. Please visit my site xl bullies for sale (https://kingbuiltbullies.com/xl-bully-breedings/)