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

4:28 PM

Whenever you create an Apex Class (in Visualforce terms it may be called a controller or an extension), and when you want to move your Apex Class to production it is necessary that you have a Test Method for your Apex Class. Moreover, the test coverage for your Apex Class should be NOT less than 75%.

Why is this and What's the need???

Unit test methods as it is also called, is in place to ensure that your apex code does not cause any undesired results in your production instance. A Unit Test method can be imagined of a Test script wherein you feed sample data and execute your Apex Class against the sample data. When you do so, you come to know the situations in which your Apex Class could fail or produce undesired results.

Imagine you have an Apex Class which performs something like outlined in the Flow Diagram below.

In such a case, your Test Method will first give the sample value (a =3, b=2) and run the Apex Class. This time you cover the "Yes" branching. The second time you will give the value ( a =2, b =3). This time you cover the "No" branching. Now, you have given sample data such that it covers both outcomes of a condition.

This concept is called "Apex Test Coverage". Now, that you have given sample data twice and covered both outcomes your test coverage would be 100%. Had you given only one set of sample values, your test coverage would be 50%.

The Need:

Salesforce wants you to ensure that the Apex Code that you deploy to your production instance will not cause any unexpected behavior to you as well as to the them. That's the simple reason behind this. Writing test methods becomes frustrating at times, but still you will have to do it.