2

I have created a functionality where in the current user's(who doing the action) territory is queried and is updated on the account object. The functionality is working fine but i am facing an issue in covering it with test method, how do i create a user and attach that user to a dummy territory?? Currently UserTerritory Object doesnt allow any DML operation so how to attach a user to a territory in test method.

user u = JJ_TestData.createUser('test7896','System Administrator');
        system.runas(u){
            account acct = new account(name='123456',Specialty_1_JJ__c='Food');
            insert acct;
            ApexPages.StandardController sc = new ApexPages.StandardController(acct);
            JJ_Territory_Assign myExt = new JJ_Territory_Assign(sc);
            myExt.includeTerritory();
            myExt.excludeTerritory();
        }      

i need the above user u which is being used in the test method to be able to attach to any territory in the org. Is that possible with the Userterritory table being DML write proof??

1

Note, this requires you to use " @IsTest with (See All Data = true) "

Try something like the following:

User u0 = [Select Id, Name, ProfileID, RoleID from User where User.Territory_Assign ='Desired Territory Name You Want to Test' and 'any other user criteria that's important']; 

system.runas(u0){
    // run the rest of your test as above to test the functionality
    // your user is already assigned to the proper territory

}     

EDIT 11-04-2016

There's now a UserTerritory Object that tracks User assignments to Territories. You'd no longer need to use SeeAllData=true to test this kind of functionality. It could be created from within a test class instead.

| improve this answer | |
  • There are two problems i see 1. We are querying user's which is not best practice since test method will fail if we deploy the class to a sandbox where there are just system admins and who don't need any territory assigned to them. 2. We would require to query on the UserTerritory object to identify the user who is associated territory is know. So when you make a query on User for User.Territory_Assign the query throws an error simply because its not find territory on User table. – Anil Shivaraj Jul 30 '13 at 15:43
  • In a sandbox, I'd expect you'd have the ability to go in and create a user and assign a territory to them. In my experience, at least some, if not all, users get copied into the sandbox. I recommend you check your user list in the sandbox to see if they're there as it may depend on the size of the org. This was a suggested solution. If it doesn't appeal to you, hopefully someone else will have one you'll like better. – crmprogdev Jul 30 '13 at 18:04
  • I think this might be out of date now, I'm getting an error "No such column 'Territory_Assign' on entity 'User'" in dev console. Any ideas? – Aislinn Hayes Nov 4 '16 at 12:12
  • 1
    Yes, it is out of date. There's now a UserTerritory Object that would control this. You'd no longer need to use SeeAllData=true to test this. You could create it in your test class instead. – crmprogdev Nov 4 '16 at 13:30
0

Refer this snippet!

@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 ;


    }

}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.