How to write a test class in Salesforce

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:


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.


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”.


private class TemperatureConverterTest {

    @isTest static void testWarmTemp() {

        Decimal celsius = TemperatureConverter.FahrenheitToCelsius(70);





If the code executes perfectly we get this output in the console.

How to write a test class in Salesforce

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”.



  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.