Wednesday, December 11, 2013

Test Class for Before Trigger in Salesforce

Test Class:

    In the previous post I have posted one Before Trigger .For that Trigger the test class is given Below.

Test Class Code:

  @IsTest
private class Account_Trigger_Test 
{
	private static testMethod void testDelete()
	{
           Account acc=new Account(Name='Test Account;);
           insert acc;
 
           // should succeed
           delete acc;
        }

	private static testMethod void testDeleteFail()
	{
           Account acc=new Account(Name='Test Account',
                                   Client_ID__c='Should fail');
           insert acc;
 
           try
           {
              delete acc;
              // should throw an exception - the following assertion will cause an error if the code carries on
              System.assert(false);
           }
           catch (DMLException e)
           {
               // expected - could assert the message here
           }
        }
}

Before Delete Trigger in Salesforce

Scenario:
    
Write a Trigger on Account Object, All it does is to prevents the Delete of an Account if a particular field(i.e.,Client_ID__c) is not Null.

Trigger Code:


trigger AccountTrigger on Account (before delete) 
{ 
   if(System.Trigger.IsDelete)
   { 
     for (Account acc : trigger.old)
  {
    if (String.isNotBlank(acc.Client_ID__c))
     { 
  acc.addError('You cannot delete This Account Please contact your Salesforce.com Administrator for assistance.');
     }
         } 
   }
 }

Notes:

Trigger.oldReturns a list of the old versions of the sObject records.Note that this sObject list is only available in update and delete triggers.
Trigger.isDeleteReturns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.

For more information/samples on trigger please check out here



Please comment or write us if you have any queries/requirements.

Please follow,bookmark,subscribe this site to receive daily updates.

Facebook - https://www.facebook.com/ILoveCodingYou/?ref=bookmarks


Hope this helps you..Enjoy..!