Testing Apex – Apex Unit Test

Testing is the key to successful long term development and is critical component of development process. Salesforce Apex, provides a testing framework which allows developers to write Apex unit test, run tests, check test results and code coverage.

In this Salesforce tutorial, we will understand testing in Apex, what to Test in Apex and What are Apex Unit Tests.

Testing Apex

Testing is the key to success for an application. If we want to validate the working of an application, then we can test an application in two ways.

  1. Using Salesforce user interface.
  2. Testing bulk Functionality.

When an application is tested using Salesforce user interface, this will not catch all cases that are important to application. Through bulk functionality we can pass up to 200 records only through our code.

Before deploying code or package to the Force.com AppExchange, the following conditions must be true.

  • At least 75% of your Apex code must be covered by unit tests.
  • All the test cases will be successful.
  • Every trigger must have some test coverage.
  • All classes and triggers must compile successfully.
ADVERTISEMENT

Factors that need to be tested in Apex Programming.

  • Single action – This is to test a single record, produces the correct expected result.
  • Bulk actions – Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. We must test not only single record case but also bulk cases.
  • Positive behaviour – Test to verify that the expected behaviour occurs through every expected permutation or not.
  • Negative behaviour – Some limits are applicable to an application like future date must not be added.
  • Restricted User – Test whether a user with restricted access to the sObjects used in your code sees the expected behavior.

What are Apex Unit test?

Apex supports creating and executing Apex unit test for robust and error free code. So what is Apex unit tests? Apex unit test is a class method which verify the working behaviour of the Apex code.Apex unit test takes no arguments, no data to database and sends no email.

When we want to create a test method in Apex, we must use testmethod Keyword or @isTest annotation. All test methods are static and can’t be defined in triggers.

Example

public class myclass {
	Static testmethod void myTest() {
		//test method logic using System.assert(),System.assertEquals()
		//and System.assertNotEquals()
	}
}

@isTest annotation

If we define any method as @isTest then the method is termed as testmethod.

example

@isTest
private class myClass {
     static testMethod void myTest() {
        // code_block
    }
}