Table of Contents
What is a test class in Salesforce?
Apex testing framework allows you to test the code before deploying to ensure the quality of the code. No code is deployed before testing the code using the test classes. Initially, apex code is written in the Sandbox environment or in the developer org, then after testing only it is deployed into the production org.
Steps to write a test class in Salesforce
Writing Test classes is simple in apex as it has a wonderful framework for it, you just simply need to annotate with “@isTest” before the class name and method name. By doing this compiler knows that it is a test class and not to make any changes in the org.
One more thing to consider is omitting the access modifier for the methods as there won’t be any need for those in these test codes.
We can also use “System.assertEquals” to check whether the method gives a response or not. It takes two values comma separated where the first one is the expected value and the other is what the code returns.
Note: Alternatively we can also use the “testMethod” keyword for the methods in the test classes for flexibility instead of annotating with “@isTest”.
Test Method Syntax
As said earlier, it is simple to write:
@isTest private class MyTestClass { @isTest static void myTest() { // code_block } }
Here, firstly we used “@isTest” annotation and then the same for the methods also. Methods do not write anything in the test classes.
Example
Creating a Class named “TemperatureConverter”.
public class TemperatureConverter { // Takes a Fahrenheit temperature and returns the Celsius value. public static Decimal FahrenheitToCelsius(Decimal fh) { Decimal cs = (fh - 32) * 5/9; return cs.setScale(2); } }
Creating a Test Class named “TemperatureConverterTest”.
@isTest private class TemperatureConverterTest { @isTest static void testWarmTemp() { Decimal celsius = TemperatureConverter.FahrenheitToCelsius(70); System.assertEquals(21.11,celsius); } }
Output
If the code executes perfectly we get this output in the console.
Code Explanation
Explanation for the class:
It takes the Fahrenheit value and returns the Celsius value with 2 decimals.
Explanation for the Test class:
Test code has a method “testWarmTemp” which sends a test value to the class to be tested and verifies the output with the expected value using “System.assert”.
Reference
https://www.sfdc99.com/2013/05/14/how-to-write-a-test-class/
https://trailhead.salesforce.com/en/content/learn/modules/apex_testing/apex_testing_intro
0 Comments