I am trying to write a test class for OpportunityTerritory2AssignmentFilter

It implements the TerritoryMgmt.OpportunityTerritory2AssignmentFilter and is a sample class provided by salesforce. Has any one used this Class before OpportunityTerritory2AssignmentFilter ?

If anyone has worked on this before any help, references or suggestions are highly appreciaed ! :)

You can find this class here or below...


    /*** Apex version of the default logic.
* If opportunity's assigned account is assigned to
*  Case 1: 0 territories in active model
*            then set territory2Id =   null
*  Case 2: 1 territory in active model
*            then set territory2Id =   account's territory2Id
*  Case 3: 2 or more territories in active model
*            then set territory2Id =   account's territory2Id that is of highest priority.
*            But if multiple   territories have same highest priority, then set territory2Id = null 
global class OppTerrAssignDefaultLogicFilter implements
TerritoryMgmt.OpportunityTerritory2AssignmentFilter {
     * No-arg constructor.
     global   OppTerrAssignDefaultLogicFilter() {}

      * Get mapping of   opportunity to territory2Id. The incoming list of opportunityIds contains only those with IsExcludedFromTerritory2Filter=false.
      * If territory2Id =   null in result map, clear the opportunity.territory2Id if set.
      * If opportunity is not present in result map, its territory2Id remains intact.
    global Map<Id,Id> getOpportunityTerritory2Assignments(List<Id> opportunityIds) {
        Map<Id,   Id> OppIdTerritoryIdResult = new Map<Id, Id>();

        //Get the active territory model Id
        Id   activeModelId = getActiveModelId();

        if(activeModelId   != null){
            List<Opportunity>   opportunities =
              [Select Id, AccountId, Territory2Id from Opportunity where Id   IN
            Set<Id>   accountIds = new Set<Id>();
            //Create   set of parent accountIds
            for(Opportunity opp:opportunities){
                if(opp.AccountId   != null){

                Map<Id,Territory2Priority> accountMaxPriorityTerritory = 
getAccountMaxPriorityTerritory(activeModelId, accountIds);

            //for each opportunity, assign the highest priority territory if there is 
no conflict, else assign null
            for(Opportunity opp: opportunities){
               Territory2Priority tp = accountMaxPriorityTerritory.get(opp.AccountId);
               //assign highest priority
              territory if there is only 1
              if((tp   != null) && (tp.moreTerritoriesAtPriority == false) && 
(tp.territory2Id != opp.Territory2Id)){
                   OppIdTerritoryIdResult.put(opp.Id, tp.territory2Id);
                   OppIdTerritoryIdResult.put(opp.Id,   null);
        return   OppIdTerritoryIdResult;

      * Query assigned territoryIds in active model for given accountIds
      * Create a map of accountId to max priority territory 
     private Map<Id,Territory2Priority> getAccountMaxPriorityTerritory(Id
activeModelId, Set<Id> accountIds){
        Map<Id,Territory2Priority> accountMaxPriorityTerritory = new 
        for(ObjectTerritory2Association ota:[Select ObjectId, Territory2Id, 
Territory2.Territory2Type.Priority from ObjectTerritory2Association where objectId IN 
:accountIds and Territory2.Territory2ModelId = :activeModelId]){
            Territory2Priority tp = accountMaxPriorityTerritory.get(ota.ObjectId);

            if((tp   == null) || (ota.Territory2.Territory2Type.Priority > 
                //If this is the first territory examined for account or it has 
greater priority than current highest priority territory, then set this as new highest 
priority territory.
                tp = new 
            }else if(ota.Territory2.Territory2Type.priority == tp.priority){
                //The priority of current highest territory is same as this, so set   
moreTerritoriesAtPriority to indicate multiple highest priority territories seen so far.
                tp.moreTerritoriesAtPriority = true;

            accountMaxPriorityTerritory.put(ota.ObjectId,   tp);
        return accountMaxPriorityTerritory;

     * Get the Id of the Active Territory Model. 
     * If none exists, return   null;
   private Id getActiveModelId() {
       List<Territory2Model>   models = [Select Id from Territory2Model where State = 'Active'];
       Id activeModelId = null;
       if(models.size()   == 1){
           activeModelId = models.get(0).Id;

       return activeModelId;

    * Helper class to help   capture territory2Id, its priority, and whether there are more territories with same priority assigned to the
   private class Territory2Priority {
       public Id territory2Id { get; set; }
       public Integer priority { get; set; }
       public   Boolean moreTerritoriesAtPriority { get; set; }

              Territory2Priority(Id territory2Id, Integer priority, Boolean moreTerritoriesAtPriority){
           this.territory2Id = territory2Id;
           this.priority = priority;
           this.moreTerritoriesAtPriority = moreTerritoriesAtPriority;

My Test class:

   **My Test Class :**

Private class OppTerrAssignDefaultLogicFiltertest{
Private static testmethod void oppTerrAssigntest(){

Opporunity opp =new Opporunity(name='testopporunity');
insert opp;
List<id> opplistid=new List<id>();

Account acc =new Account(name='testaccount');
insert acc;
Set<id> acclistid=new Set<id>();

OppTerrAssignDefaultLogicFilter CheckOppty=new OppTerrAssignDefaultLogicFilter();
Map<Id,Id> mapid=CheckOppty.getOpportunityTerritory2Assignments(opplistid);
Map<Id,Territory2Priority>MapTerritory=CheckOppty.getAccountMaxPriorityTerritory(vn897, acclistid)
Id id=CheckOppty.getActiveModelId();

OppTerrAssignDefaultLogicFilter.Territory2Priority innerclass=new OppTerrAssignDefaultLogicFilter.Territory2Priority(Vn897,9908,true);


I'm getting the following error:

invalid type : Territory2Priority

  • So, have you actually tried writing the test class yourself ? You can't really come here and expect people to do the work for you. That's not how a community works, that's how contractors work. We're all about helping you, helping you learn and figure things out. Feel free to edit the question if you do have a specific question on how to proceed. Commented Jun 11, 2015 at 17:34
  • @SamuelDeRycke With all due respect, I dont expect you to work for me nor any one for that matter! I don't expect all ready code from you either ! I ain't a contractor for your info , and not interested in such insinuations provided! I'm just like someone who is new to this topic and expect people to give me reference or help understanding! I did write Test class for this but stuck in between, I would rather show you the code and ask suggestions if you have any interest in helping people rather than rephrasing the question just because someone said,my question is very straight!! Thanks!
    – SFDC Wolf
    Commented Jun 12, 2015 at 9:36
  • 1
    Maybe I've phrased my comment to harsh, but the only straight forward question is see is that you have a class and need a test class. You have not asked how you can do this yourself, or where you can start learning to write test classes, which would be an entirely different question. You say you're trying to write a test class, but have not shared it with us or explained what troubles you're having in writing that class. If you'd share that, we'd love to help you, but if you don't there's little we can do. Getting helped is a matter of askign the right questions, that's all I wanted to say. Commented Jun 12, 2015 at 9:44
  • You can still edit and update the question, so that the community can reopen it. Commented Jun 12, 2015 at 9:45
  • @SamuelDeRycke I'm glad that you know your phrase was too harsh, no offense taken! This is a sample class provided by salesforce in the latest Summer 15' release and it is not implemented or released yet, this is something I have never worked on 'Territory Assignment Default logic filter' . Still I tried writing test class and reached somewhere! I take some mistake on myside as well as the question could be understood the other way also which asks test class reference. I did not understand flagging it as off topic and putting the post on hold!
    – SFDC Wolf
    Commented Jun 12, 2015 at 10:02

3 Answers 3


Ok So the internal class of Territory2Priority ( the type) is noted as Private and you are trying to access this in a test class.

Private will make it only visible inside its class constant.

+1 salesforce here, Add @TestVisible on top of the private and you will be able to access the class from your test.

Updating the second part

In the test you are calling the class inside a map MapTerritory You need to add infront of this call where it site I.E the class name So your map should look like this

Map<Id, OppTerrAssignDefaultLogicFilter.Territory2Priority >MapTerritory=CheckOppty.getAccountMaxPriorityTerritory(vn897, acclistid)

Next you are going to get more calls saying could not find methods because they are set to be private. Make them all @TestVisible private Or public. Finial


Needs to be checked not just called.So these become

System.assertEqual(Vn897 ,innerclass.territory2Id, 'Fail');
System.assertEqual(9908 ,innerclass.priority, 'Fail');
System.assertEqual(true ,innerclass.moreTerritoriesAtPriority, 'Fail');

Also in the Class the constructor for Territory2Priority is not visible give it ether public or @TestVisible Private

Apologies, Forgot that the class is Global, so inner class must be global. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_defining.htm

  • Hi @Tim , Got it ! I tried doing that but the error still pops up "invalid type : Territory2Priority"
    – SFDC Wolf
    Commented Jun 12, 2015 at 13:11
  • Is it on saving the test or during run time, If run time could you provide the stack trace Commented Jun 12, 2015 at 13:22
  • MapTerritory variable in your test (that you provided ) is missing ; Commented Jun 12, 2015 at 13:26
  • Its on saving the test.
    – SFDC Wolf
    Commented Jun 12, 2015 at 13:27
  • line 21? - Map<Id,Territory2Priority> MapTerritory should be Map<Id, CheckOppty.Territory2Priority>MapTerritory Commented Jun 12, 2015 at 13:30

Since I can't found an OOTB test class for this anywhere, I just wrote one up real quick.

Requirement in OpportunityTerritory2AssignmentFilter class:

You will need to mark the inner class and its constructor @TestVisible

private class Territory2Priority {
    public Id territory2Id { get; set; }
    public Integer priority { get; set; }
    public Boolean moreTerritoriesAtPriority { get; set; }

    Territory2Priority(Id territory2Id, Integer priority, Boolean moreTerritoriesAtPriority) {

Test Class:

public class OpportunityTerritory2AssignmentFilterTests {

static void unitTest() {
    Id opportunityId = [Select Id From Opportunity].Id;
    OpportunityTerritory2AssignmentFilter filter = new OpportunityTerritory2AssignmentFilter();


    Map<Id, Id> resultMap = filter.getOpportunityTerritory2Assignments(new List<Id> {opportunityId});
    OpportunityTerritory2AssignmentFilter.Territory2Priority tp = new OpportunityTerritory2AssignmentFilter.Territory2Priority(opportunityId, 1, false);


    System.assertEquals(1, resultMap.size());
    System.assertEquals(tp.territory2Id, opportunityId);
    System.assertEquals(1, tp.priority);
    System.assertEquals(false, tp.moreTerritoriesAtPriority);

static void setup() {
    Account account = new Account(Name = 'testAccount');
    insert account;

    Opportunity opp = new Opportunity(
        Name = 'Opportunity',
        CloseDate = System.today().addDays(10),
        StageName = 'Prospecting',
        AccountId = account.Id
    insert opp;

Hopefully this will save somebody a few minutes somewhere down the road.

  • - Thanks, I needed that few minutes back in my day. :) Commented Mar 21, 2017 at 22:23

Below is test class which have 92% coverage. but you need to add @TestVisible in apex class for each method.

@isTest Public class Test_OppTerrAssignDefaultLogicFilter {

Public static testmethod void oppTerrAssigntest(){
    Account account = new Account(Name = 'testAccount');
    insert account;
    Opportunity opp = new Opportunity(
        Name = 'Opportunitytest',
        CloseDate = System.today().addDays(10),
        StageName = 'Discovery & Qualification',
        AccountId = account.Id
    insert opp;
    List<id> opplst   = new List<id>() ;
    Set<Id> accountIds = new Set<Id>();
    User usr = [Select id from User where Id = :UserInfo.getUserId()];
        List<Territory2Type> terriType   = [SELECT id, DeveloperName from Territory2Type];
        Territory2Model terrModel   = new Territory2Model(DeveloperName='ModelName',Name = 'Name');
        insert terrModel;
        Territory2 objTerr =new Territory2(DeveloperName = 'TestTerritory', Territory2ModelId=terrModel.Id, Name='TestTerritory',Territory2TypeId=terriType[0].Id,Region__c='',Segment__c='',Sub_Region__c='',Theater__c='');
        insert objTerr;
        ObjectTerritory2Association objObjectTerritory2Association = new ObjectTerritory2Association(ObjectId = account.Id,Territory2Id =objTerr.Id,AssociationCause='Territory2Manual');
        insert objObjectTerritory2Association;
        OppTerrAssignDefaultLogicFilter filter = new OppTerrAssignDefaultLogicFilter();
        Map<Id, Id> resultMap = filter.getOpportunityTerritory2Assignments(new List<Id> {opp.Id});
        filter.getAccountMaxPriorityTerritory(terrModel.id, accountIds);


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .