Thursday, January 22, 2015

Writing Test Classes in salesforce



Testing is an important part of the development process. Before you can deploy Apex or package it for the Force.com AppExchange, the following must be true.

·        
  • At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
  • Every trigger must have some test coverage.
  • All classes and triggers must compile successfully
Learning to write a Test class for Apex Code


Identify the operation on which a trigger is fired and Apex code is executed.In Test Class same scenario needs to be re-produced so that that trigger is fired and all possible conditions are checked in apex code.During a test call data is not written on salesforce database.



Step 1:- @isTest Annotation
This class is defined using the @isTest annotation. Classes defined as such can only contain test methods. One advantage to creating a separate class for testing is that classes defined with isTest don't count against your organization limit of 3 MB for all Apex code

Step 2: Defining the Test Class

Step 3:-Defining the test Method.
This method is defined as a testMethod. This means that if any changes are made to the database, they are automatically rolled back when execution completes and you don't have to delete any test data created in the test method.



Example-

Trigger
trigger testTrigger on Cars (before insert,before update) {
List<Cars__c> Cr=[select id from cars where id=:Trigger.New];
List<Cars__c> updatecars=new List<Cars__c>
For(cars__C C:cr)
{
c.Price__c= c.Price__c-10000;
updatecars.add(c);
}
Update updatecars;
}

Test Class

@isTest ---------------Step 1
private class HelloWorldTestClass {--------------------step 2
    static testMethod void validateHelloWorld() {----------------step 3
       Cars__c c = new Cars__c(Name='BMW', Price__c=$100000);
       System.debug('Price before inserting new car: ' + c.Price__c);

       // Insert car
       insert c;
   
       // Retrieve the new car
       c = [SELECT Price__c FROM Car__c WHERE Id =:c.Id];
       System.debug('Price after trigger fired: ' + c.Price__c);

       // Test that the trigger correctly updated the price
       System.assertEquals(900000, c.Price__c);
    }
}


No comments:

Post a Comment