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
mohammadd ismailmohammadd ismail 

Writing Efficient Test Classes

I am new to salesforce, how to write a test class in apex and what are the things that have to be considered while writing a test class.
Best Answer chosen by mohammadd ismail
NagendraNagendra (Salesforce Developers) 
Hi Ismail,
  • All test methods should reside in a separate class from the class in which the method being tested resides.
  • These classes should be appended with the word Test followed by the name of the class being tested, e.g. OpportunityServicesTest.
  • These classes should all use the @isTest annotation.
  • Each method in the production class should have, at a minimum, one corresponding test method in its test class and should be appended by “test.”
  • There should be a minimum of “Null Pointer Exception test” as part of negative testing for each method, specially the methods that accept parameters.
  • A method without an assert statement is not considered a test method. A large number of relevant assert statements increases confidence in the correct behaviour of business logic.
  • There should be a comment with each assert statement explaining what is being tested and what the expected output is
  • Only use isTest(SeeAllData = true) on class methods in exceptional cases where there are sObjects that don't allow DML operation e.g. PriceBook creation
  • No hard coded ids of any sObject in any test method.
  • If a Constant needs to be asserted , its a best practice to reference that from the Constant class or from Custom Labels or Custom Settings. Using hard coded string in unit tests( or any class for that matter) will trigger failures when things like Picklist values change
  • All test data creation should be done from a Utility class. This allows for a streamlined creation of test objects that adhere to all the validation rules.
  • Any business logic that needs to be tested should be enveloped within a Test.runAs(user) statement so profile restrictions can be tested. Using any admin profiles should be avoided.
  • All private methods should also have its corresponding unit test method. In the production code, add a public method for each private method and prepend it by “exposeForUnitTest_”.
  • Creating multiple test method for testing that same production code method should be avoided. We want to ensure that our unit test methods are properly testing the logic but the same time the efficiency of the unit test method should not be ignored. All the unit test methods run with every deployment so the cumulative run time should be as small as possible
  • Any asynchronous method testing should include Test.startTest and Test.stopTest. Test.stopTest forces the asynchronous methods to run so the results could be asserted.
  • Any exceptions that are caught in the production methods should be tested by feeding the test data that throws exception. Exception Type and the error message should be asserted.
  • Every class should have test coverage close to 95% as possible. The focus should be on asserting method behaviour rather than increasing coverage. There are very few instances where a method behaviour is not straightforward to reproduce and hence test. These should be properly commented.
How to write test classes in Salesforce: Please refer to the below link which helps you understand how to write test classes in Apex
http://rainforce.walkme.com/how-to-write-test-class-in-salesforce/

Please mark my solution as the best answer if it helps you.

Best Regards,
Nagendra.P

All Answers

NagendraNagendra (Salesforce Developers) 
Hi Ismail,
  • All test methods should reside in a separate class from the class in which the method being tested resides.
  • These classes should be appended with the word Test followed by the name of the class being tested, e.g. OpportunityServicesTest.
  • These classes should all use the @isTest annotation.
  • Each method in the production class should have, at a minimum, one corresponding test method in its test class and should be appended by “test.”
  • There should be a minimum of “Null Pointer Exception test” as part of negative testing for each method, specially the methods that accept parameters.
  • A method without an assert statement is not considered a test method. A large number of relevant assert statements increases confidence in the correct behaviour of business logic.
  • There should be a comment with each assert statement explaining what is being tested and what the expected output is
  • Only use isTest(SeeAllData = true) on class methods in exceptional cases where there are sObjects that don't allow DML operation e.g. PriceBook creation
  • No hard coded ids of any sObject in any test method.
  • If a Constant needs to be asserted , its a best practice to reference that from the Constant class or from Custom Labels or Custom Settings. Using hard coded string in unit tests( or any class for that matter) will trigger failures when things like Picklist values change
  • All test data creation should be done from a Utility class. This allows for a streamlined creation of test objects that adhere to all the validation rules.
  • Any business logic that needs to be tested should be enveloped within a Test.runAs(user) statement so profile restrictions can be tested. Using any admin profiles should be avoided.
  • All private methods should also have its corresponding unit test method. In the production code, add a public method for each private method and prepend it by “exposeForUnitTest_”.
  • Creating multiple test method for testing that same production code method should be avoided. We want to ensure that our unit test methods are properly testing the logic but the same time the efficiency of the unit test method should not be ignored. All the unit test methods run with every deployment so the cumulative run time should be as small as possible
  • Any asynchronous method testing should include Test.startTest and Test.stopTest. Test.stopTest forces the asynchronous methods to run so the results could be asserted.
  • Any exceptions that are caught in the production methods should be tested by feeding the test data that throws exception. Exception Type and the error message should be asserted.
  • Every class should have test coverage close to 95% as possible. The focus should be on asserting method behaviour rather than increasing coverage. There are very few instances where a method behaviour is not straightforward to reproduce and hence test. These should be properly commented.
How to write test classes in Salesforce: Please refer to the below link which helps you understand how to write test classes in Apex
http://rainforce.walkme.com/how-to-write-test-class-in-salesforce/

Please mark my solution as the best answer if it helps you.

Best Regards,
Nagendra.P
This was selected as the best answer
Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about Test classes.
1) http://amitsalesforce.blogspot.com/search/label/Test%20Class
2) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Please check 2nd post for test class example

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required 
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

 
ABLABL
Hi Mohammadd,

As Nagendra mentiond you should follow best practices while writing test class in SFDC . However, I had develop one tool named "Test Class Generator" in salesforce to write test classes using point and click. In order to generate test class for your controller we need to follow some simple, for now, its been working for code coverage perspective only. In my next releases I'll cover proper unit testing. Please spare some time to look over my app on appexchange and provide some feedback. https://www.youtube.com/watch?v=Q8t5iNC0Vys https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000EFozgUAD

Thanks...
farukh sk hdfarukh sk hd
Please go through the below post which will help you understand about test class.

SeeAllData in test classes,

https://www.sfdc-lightning.com/2018/09/testing-in-salesforce-with-seealldata.html

About test class,

https://www.sfdc-lightning.com/2018/09/testing-in-salesforce.html

 
Ajinkya DhasAjinkya Dhas
Hi,

Please visit the link below to understand :
- When to write Apex Test Class ?
- Which factors to be tested while writing Test class ?
- How to use @isTest Annotation in salesforce ?
- How to write apex Test Class ?


https://www.salesforcekid.com/2019/09/how-to-write-test-class-basics-salesforce.html

I hope this will help you to learn how to write a test class very easily

Thanks 😊,
AJINKYA DHAS
[SalesforceKid (http://www.salesforcekid.com)]