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
SFDC 2017SFDC 2017 

Help on territory related methods on test class >Less coverage

Hi All,
I am not able to cover the Territory related methods which are in my controller .Can anyone please guide me to cover the below methods related to territory in Test class.

public void getTerritories(){
        List<UserTerritory> userTerritories = [select TerritoryId From UserTerritory where isActive=true and userId =:UserInfo.getUserId()];
        List<Territory> territories = new List<Territory>();
        if(!userTerritories.isEmpty()){
            for(UserTerritory userTerritory : userTerritories){
                territories.addAll(getTerritoryHierarchy(userTerritory.TerritoryId));
            }
        }
        territoryOptions = new List<SelectOption>();
        for(Territory territory : territories){
            if(territoryOptions.size()<1000){
                territoryOptions.add(new SelectOption(territory.Id, territory.Name));
            }
        }
    }
public List<Territory> getTerritoryHierarchy(Id highTerrId){
        List<Territory> territories = new List<Territory>();
        Map<Id, Territory> territoriesMap = new Map<Id, Territory>([select Id, ParentTerritoryID, Name from Territory]);
        Territory Terr = territoriesMap.get(highTerrId);
        territories.add(Terr);
        List<Territory> childTerrs = new List<Territory>();
        for(Territory childTerr : territoriesMap.values()){
            if(childTerr.ParentTerritoryId == Terr.Id){
                childTerrs.add(childTerr);
            }
        }
        territories.addAll(childTerrs);
        list<territory> territorylst = new list<territory>();
        territorylst = getTerritoryHierarchy1(childTerrs);
        territories.addAll(territorylst);
        do{
            territorylst = getTerritoryHierarchy1(territorylst);
            territories.addAll(territorylst);
        }while(!territorylst.isEmpty());
public List<Id> getAccFrmTerritories(List<Id> territoryIds){
        List<Group> territoryGroups = [select Id from Group where RelatedId in :territoryIds AND Type='Territory'];
        List<Id> accountIds = new List<Id>();
        if(territoryGroups != null){
            List<Id> territoryGroupIds = new List<Id>();
            for(Group territoryGroup : territorygroups){
                territoryGroupIds.add(territoryGroup.Id);
            }
            List<AccountShare> accountShares = [select AccountId from AccountShare where UserOrGroupId in :territoryGroupIds];
            for(AccountShare accountShare : accountShares){
                accountIds.add(accountShare.AccountId);
            }
        }
        return accountIds;
    }
Rahul.MishraRahul.Mishra
Hi,

To achive the test coverage, you have to associate your user  (or create new in test class) with territory using UserTerritory2Association  object then only you will get the data in your query, below is the sample code where we have associated a user with newly created territory, you can refer the code to update your test class:
 
@isTest
private class SL_Test_TerritoyTriggerAndBatch {

    private static final Id ACCOUNT_BROKER_RECORDTYPE = [Select Id, DeveloperName from RecordType where sObjectType='Account' and DeveloperName='Broker' LIMIT 1].Id;

    private static testMethod void territorryAssignmentToAccountsByTrigger() {

        Account objAccount = new Account(RecordTypeId = ACCOUNT_BROKER_RECORDTYPE, Name = 'Test Acc - 01', ShippingState = 'USA');
        insert objAccount;
        User usr = [Select id from User where Id = :UserInfo.getUserId()];

        System.RunAs(usr)
        {
            Test.startTest();
               insertTestTerritory(objAccount.Id);
            Test.stopTest();
        }
    }

    //@future
    private static void insertTestTerritory(Id AccId)
    {
        List<Territory2Type> terriType   = [SELECT id, DeveloperName from Territory2Type where  DeveloperName = 'Broker_Assignments' LIMIT 1];
        List<Profile> adminProfile = [select id, name from Profile where  name = 'System Administrator'];

        Territory2Model terrModel = new Territory2Model();
        terrModel .DeveloperName='ModelName'; // required field
        terrModel.Name = 'Name'; // required field
        insert terrModel ;

        Territory2 objTerr = new Territory2(DeveloperName = 'TestTerritory', Territory2ModelId=terrModel.Id, Name='TestTerritory', Territory2TypeId=terriType[0].Id);
        insert objTerr;

        ObjectTerritory2Association objObjectTerritory2Association = new ObjectTerritory2Association(ObjectId = AccId, Territory2Id =objTerr.Id, AssociationCause='Territory2Manual' );
        insert objObjectTerritory2Association;

        Profile p = [SELECT id, Name FROM Profile where name = 'System Administrator' ].get(0);  
        User u = new User(firstname= 'Test',
                  lastname='XXXX',
                  Alias='Test',
                  email = 'test1234@test.com',
                  username= 'test1234xxx@test.com', 
                  profileId= p.id, 
                  emailencodingkey='UTF-8',
                  languagelocalekey='en_US',
                  localesidkey='en_US',
                  timezonesidkey='America/Los_Angeles');
        insert u;

        User u2 = new User(firstname= 'Test',
                  lastname='XXXX',
                  Alias='Test',
                  email = 'test1234122@test.com',
                  username= 'test1234xxx123@test.com', 
                  profileId= p.id, 
                  emailencodingkey='UTF-8',
                  languagelocalekey='en_US',
                  localesidkey='en_US',
                  timezonesidkey='America/Los_Angeles');
        insert u2;


        UserTerritory2Association objUserTerritory2Association = new UserTerritory2Association(Territory2Id= objTerr.Id, UserId= u.Id, RoleInTerritory2='Sales / Marketing Manager');
        insert objUserTerritory2Association;

        UserTerritory2Association objUserTerritory2Association2 = new UserTerritory2Association(Territory2Id= objTerr.Id, UserId= u2.Id, RoleInTerritory2='Sales / Marketing Administrator');
        insert objUserTerritory2Association2 ;


    }

}

Mark solved if it does help you.