You need to sign in to do that
Don't have an account?
gowtham 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.');
}
}
}
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.');
}
}
}
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:
Test class:
Please mark it as best answer if you found it helpful.
The test class should be like below and you will get 100% coverage :
Thanks,
Maharajan.C
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.
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