5.1 Write unit test for a class

Why unit test

Salesforce requires at least 75% code coverage of all the Apex code. So in short, in Salesforce world, you must write unit test. For me, I firmly believe it is a good practice that every org and company should follow. The earlier you find a bug, the easier you can fix it. It will finally save you a lot of time and effort and money if you do the unit tests properly.

For more reasons you should perform unit testing, refer to this stackoverflow discussion.

How to write a unit test

I will show you how to write unit test for an Apex class by demonstrating a simple example.

First, let’s create a simple class called MathCalculator. We are going to test this class.

public class MathCalculator 
    public Decimal add(Decimal a, Decimal b)
        return a + b;
    public Decimal minus(Decimal a, Decimal b)
        return a - b;
    public Decimal multiply(Decimal a, Decimal b)
        return a * b;

Now let’s write our unit test. We do this by creating a new Apex class called TestMathCalculator. The class name doesn’t matter, you can name it anything. But for better readability, it is usually advisable to name it either TestMathCalculator or MathCalculatorTest.

public class TestMathCalculator 
    static void testCalculator()
        MathCalculator mc = new MathCalculator();
        System.assertEquals(5, mc.add(2, 3));
        System.assertEquals(3, mc.minus(7, 4));
        System.assertEquals(18, mc.multiply(3, 6));

Once you save the class in Developer console, you will notice a Run Test button now appears. Click that button.

After it finishes, switch to your Tests panel in Developer console. You can find The latest test run has a green success and the test coverage for MathCalculator is now 100%.

A little bit explanation

For each test class and test method, we need to make them with an @isTest annotation. So the system knows it is served for testing purpose. For test method. You can either use @isTest or use testMethod modifier. These two can be used interchangeably.

A test method has to be static. It doesn’t matter whether it is public or private. But it needs to be static.

A test method usually has three parts, the test data generation (in this case, we created an instance of MathCalculator class), the exercise of tested methods, and the final testing part(System.assertEquals).

System.assertEquals verifies whether the result is as expected.

Next Post

5.2 Write unit test for a trigger

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

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