Test Class is an important part of the salesforce. Test Class is a class where we test our written working code that means the code is working right or not. In the Test Classes, we made the dummy data by which we check if the code is covered or not. The code coverage is performed by the Test Classes. The functionality of the apex class is tested by the code snippets of the Test Class.
Why do we need a Test Class in Salesforce?
In Salesforce, the code must have 75% code coverage in this class before deploying the code to the production org. We cannot create a package of production org also with the code coverage below 75%. Test classes don’t have access to the organization’s data. But to give access to the organization data to the test class we use @isTest(seeAllData = true) annotation.
Features Of Test Classes:-
- @isTest annotation: By this annotation, we declare that this class which tells the code compiler also that this class is for covering the code of the apex classes and it will not be used against the organization data.
- testmethod: This is the function of a test class but it doesn’t take any arguments, no data to be committed to the database. The method is declared using the testMethod keyword. These methods are defined in the test class i.e class annotated with isTest.
- Test.startTest() and Test.stopTest(): These are the standard available methods in the salesforce test class. In these methods, the event or action is contained in our class for which we will be simulating our test. For example: if we use a trigger to update the fields, as we have done to start and stop blocks. Test classes also provide separate governor limits to the code in the start and stop block.
- System.assert(): This method in the test class compares the desired output of the code with the actual output. So, we expect a record to be inserted.
How to run a test class and check the code coverage?
Note: We can run all the test classes in the organization or as well as individual test classes.
Step1. Open Developer Console, and click on the Test option from the menu and then click on the New Run.
Step2. A box will appear on the screen, select the Test Class and its Test Method and then click on Run.
Step3. It may take some time to run the test. After the test run, we will be able to check the code coverage and which method failed or passed. In the below screenshot, the left side is the methods that are passed and on the right side, the coverage of code is displaying.
Leave A Comment