Search In This Blog

2016-09-27

How to write Apex test class


An Apex test class is used to confirm if instructions and methods in an application or program are working correctly as desired. Tests can be written for many classes.

Since Salesforce require at least 75% of the code to be tested before it can be deployed to the organization. There are different test classes run to achieve the 75% minimum requirement tests on task codes.

To create an Apex class: [Setup]-[Develop]-[Apex Classes]-[New].
It can also be create through develop console, [You username]-[Develop console]-[File]-[New]-[Apex Class]

Basic strunction of test class
@isTest 
public class BaseTest { 
    // Test Method 
    public static testmethod void Test1(){ 
        // Prepara data for test
        List<Account> accounts = new List<Account>{};
        for(Integer i = 0; i < 200; i++){
            Account a = new Account(Name = 'Test ' + i);
            accounts.add(a);
        }
        Test.startTest(); 
        // Put test target here
        insert accounts;
        Test.stopTest();  
    } 
} 
@isTest – informs Salesforce the class is for test purposes
BaseTest – the name of the test class
testMethod – this is a repeat message to inform salesforce the code is for test purposes.
Test 1 - the name of the test method

To get the result of test and check if result is excepted, use the methods below:
System.assert(), System.assertEquals(), System.assertNotEquals()

If you use SeeAllData=true Annotation, all test methods in this class can access all data. It may change the data that you don't want to change during testing.
@isTest(SeeAllData=true)
public class BaseTest {...} 

Attention: Avoid to put a soql inside of loop. 

No comments:

Post a Comment