function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
gowtham kumar 14gowtham kumar 14 

Can you Help me writing test class for the below trigger

Trigger TerritoryOwnerRestrictionTrigger on Territory__c (after insert,before Update) {
    for (Territory__c T : Trigger.new)
    {
       
      Integer i = [Select count() from Territory__c where Territory__c.OwnerId !=:T.OwnerId and Territory__c.Id !=: T.Id and Territory__c.Name=:T.Name];
        System.debug('Count :'+i);
      if(i>2)
      {
         T.addError('we can not Assign a zipcode to this user, Only a single zipcode is assigned to only three Owners.'); 
      }
    }
}
sachinarorasfsachinarorasf
Hi Gowtham,

If you want to stop creating Territory record if the same zip code is already assigned to 2 records then you should use before insert in trigger because you cannot add error in after insert trigger. And also update your trigger with the below trigger code.

Trigger:
Trigger TerritoryOwnerRestrictionTrigger on Territory__c (before insert,before Update) {
    for (Territory__c T : Trigger.new)
    {
        
        Integer i = [Select count() from Territory__c where Territory__c.OwnerId !=:T.OwnerId and Territory__c.Id !=: T.Id and Territory__c.Name=:T.Name];
        System.debug('Count :'+i);
        if(i>2)
        {
            if(!Test.isRunningTest()){
                T.addError('we can not Assign a zipcode to this user, Only a single zipcode is assigned to only three Owners.'); 
            }
        }
    }
}


Test class:
 
@isTest
public class TerritoryOwnerRestrictionTriggerTest {
    
    @isTest 
    public static void test_TerritoryTrigger(){
        /* Add all other required field if you get any exception*/
        Territory__c  territoryObj1 = New Territory__c();
        territoryObj1.Name = 'test';
        
        Territory__c  territoryObj2 = New Territory__c();
        territoryObj2.Name = 'test';
        
        Territory__c  territoryObj3 = New Territory__c();
        territoryObj3.Name = 'test';
        
        Test.startTest();
        insert territoryObj1;
        insert territoryObj2 ;
        insert territoryObj3;
        Test.startTest();
    }

}



Please mark it as best answer if you found it helpful.
Maharajan CMaharajan C
Hi Gowtham,

The test class should be like below and you will get 100% coverage :
 
@isTest
public class TerritoryOwnerRestrictionTrigger {
    
    Static testmethod void territoryOwnerRestrictionTestMethod(){
        List<user> userList = new List<user>();
        Profile p= [Select Id from profile where Name='System Administrator']; 
        for(integer i = 0 ; i < 4 ; i++){
            User newUser = new User(
                profileId = p.id,
                username = Math.random()+'@'+Math.random()+'.test',
                email = 'sysAdmin'+ i +'@gmail.com',
                emailencodingkey = 'UTF-8',
                localesidkey = 'en_US',
                languagelocalekey = 'en_US',
                timezonesidkey = 'America/Los_Angeles',
                alias='SA'+ i,
                lastname='sysAdmin'+ i
            );
            system.debug(' user ==> ' + newUser);
            userList.add(newUser);
        }
        insert userList;
        Test.startTest();
        Territory__c terRecord1 = new Territory__c(name = 'testTer1', OwnerId = userList[0].Id);
        Territory__c terRecord2 = new Territory__c(name = 'testTer1', OwnerId = userList[1].Id);
        Territory__c terRecord3 = new Territory__c(name = 'testTer1', OwnerId = userList[2].Id);
        Territory__c terRecord4 = new Territory__c(name = 'testTer1', OwnerId = userList[3].Id);
        List<Territory__c> terList = new List<Territory__c>();
        terList.add(terRecord1);
        terList.add(terRecord2);
        terList.add(terRecord3);
        insert terList;
        Database.SaveResult result = Database.insert(terRecord4, false);
		Test.stopTest();
    }
}



Thanks,
Maharajan.C
Andrew GAndrew G
Goodness.

The OP and first responder have triggers that are not best practice for bulkification - they have a SOQL query inside a FOR loop - a no-no

Neither Test Class solution hints at the use of Asserts - best practice again ignored.
Andrew GAndrew G
Lets fix the trigger first
Trigger TerritoryOwnerRestrictionTrigger on Territory__c (before insert,before Update) {

   Set<ID> ownerIdSet = new Set<Id>();
   Map<Id,String> territoryByOwnerIdMap = new Map<Id,String>();
    for (Territory__c T : Trigger.new)
    {
        ownerIdSet.add(t.OwnerId);
    }

AggregateResult[] groupedResults = [SELECT OwnerId, Count(Id)
     FROM Territory__c
     WHERE OwnerId IN :ownerIdSet
     GROUP BY OwnerId];
Map<Id, Integer> mapResults = new Map<Id,Integer>();
for (AggregateResult ar : groupedResults)  {
        mapResults.put(ar.get('OwnerId'),ar.get('expr0'));
    }
 }

 for (Territory__c T : Trigger.new) { 
    if(mapResults.containsKey(t.OwnerId) {
        if(mapResults.get(t.OwnerId)>3) {
            T.addError('Person can have no more than 3 territories');
        }
    }

 } 

}
Ok, so whats the logic?
We get all the Owner Ids for the Territories being updated, as the criteria as I read it is that "A person cannot have more than 3 territories".
We then do a Aggregate Result query.
We then convert that to a Map, as you can only loop an Aggregate Result and Maps work well here.
We then loop the trigger again so that we can use the .addError function which only works for trigger components.

Note:  code is provided uncompiled and is written free-hand.

Lets sort the trigger first, then we can look to the Test classes.

Regards
Andrew