A Guide to writing Test Methods for an Apex Class in Salesforce - Part 2

3:36 PM

The Basic - Getting Started

Let's start by considering a simple apex class.

Public class mysimpleclass
{
    Public void samplemethod()
    {
        Integer a = 10;
        Integer b = a + 20;
        system.debug('The value of b is'+b);
    }
   
} 

Now, we shall write the test method for this class.

Step 1: You have two options. You can have the test method in the same class above, OR you can have a separate class which has the test method for the above class. I always go with a separate class, because

  1. It is easy to organize.
  2. Make use of @istest notation to prevent the test class from being counted against the organization apex code limit. Remeber, comments and classes with @istest notation are not counted.
Create a new apex class as below. Please note that this is the basic standard for any test class.



@istest
private class mysimpleclass_TestMethod // Name of the test class, Can be any name
{         
    static testmethod void mysimpleclass_TestMethod()   // Name of the test method. Must be the same as the class name 
    {
        mysimpleclass testcls = new mysimpleclass();   // Initialize variable for original class 
        testcls.samplemethod();                        // Call Function of Original class
    }    
}

Step 2:  Save the class and click on the "Run Test" button as shown below.


Step 3: You will  see the screen shown below.

As you can see, the test method coverage is 100%, meaning that all lines of the apex class have been covered.

Now, click on the "100" link highlighted in the "Code Coverage" section as shown above.
You will see the screen shown below..



A Blue color denotes - CODE COVERED
A RED color denotes - CODE NOT COVERED
Since our code coverage is 100% we do not have any red lines.

1 comments

  1. This is the Old method.
    Now, the method for Run Tests has Changed.
    Please update with Latest Run Tests Page.

    ReplyDelete