+ Start a Discussion
force shahidforce shahid 

How to write test class for this territory Trigger

Hi friends ,

I wrote a trigger on Territory2 object . And i create custom setting and field . In this custom setting the custom check field is checked for any particular user he only have the permission to delete option.

How to write test class for this trigger

Trigger :

trigger Triggerdelete on Territory2 (before delete) {
    id ids=userinfo.getProfileId();
    Delete_Permission__c del=Delete_Permission__c.getinstance(ids);
    if(del.Permission__c==false){
        Trigger.old[0].adderror('User Can\'t delete this Territory');
    }

}

 
sukanya banekarsukanya banekar
Hi,
I see territory2 must be your custom object.
you need to insert data in your custom setting in test class 
e.g 
Delete_Permission__c setting = new Delete_Permission__c ();
setting.Name= 'test';
setting.Permission__c= false;
insert setting;

insert data for territory2 object
Territory2 obj= new Territory2;
insert obj;

territory2 qry= [SELECT id from Territory2 where Id=:obj.Id];
Boolean error=false;

try{
delete qry;
}catch(Exception ex){
error= ex.getMessage().contains('User Can\'t delete this Territory') ? true : false;
}
and check error in system.assertEquals(true,error);


Let me know if this helps you to solve your problem

Thanks,
Sukanya Banekar
 
Amol Salve 13Amol Salve 13
Hello,
 
test class for above functioanlity is 



@isTest
public with sharing class TerritoryTestClass {
    public static testmethod void TerritoryTest(){
        
        list<Territory2Type> territory2List = [SELECT id, DeveloperName from Territory2Type where  DeveloperName = 'Territory'];
        Territory2Model terrModelObj = new Territory2Model();
        terrModelObj .DeveloperName='ModelName';
        terrModelObj.Name = 'Name';
        insert terrModelObj;
        Territory2 territory2obj = new Territory2(DeveloperName = 'Test1', Territory2ModelId=terrModelObj.Id, Name='TestTerritory', Territory2TypeId=territory2List[0].Id);
        insert territory2obj;
        test.starttest();
            
            update territory2obj;
        test.stopTest();
        // Check assert
    }
}

Thank you,
Amol Salve
Salesforce developer
force shahidforce shahid
Hi Sukanya & Amol
Thanks for your code, But Its not working . On territory2 DML delete opeation is not working.