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
bohemianguy100bohemianguy100 

Unit Test - creating and assigning a territory to an account

Can anyone point me to an example of how to create and assign a territory manually to an account in a unit test?  I have created an account in my unit test, but I also need to manually assign a territory to the account.  So, I need to create the territory, the userTerritory and user record that will be assigned to the account.

 

How do you go about doing this in a unit test.  It doesn't appear you can perform DML on the Territory and UserTerritory objects in a unit test? 

 

Can anyone provide some help on how to accomplish this in a unit test?

 

Thanks.

h8r41dh8r41d

Hi,

 

Any way you can post a code sample? I've run across the problem of not being able to perform DML on certain objects in a test environment. Usually, I just do a check on Test.IsRunningTest() when doing DML on these objects and resort to assigning a fake value just for testing.

 

I had this problem writing test code for classes that interact with the PartnerNetworkConnection and PartnerNetworkRecordConnection objects.

 

 

Gabriel Alack
Contact Us - We Can Help!
Salesforce Superheroes
------------------------------
help@salesforcesuperheroes.com
www.salesforcesuperheroes.com
1-888-407-9578 x122

bohemianguy100bohemianguy100

I've temporarily gotten around the issue by querying for an active user that is already assigned to a specific territory.  I'd prefer not to do this and instead create a testUser, and assign the testUser to a UserTerritory.  From what I've found, you cannot run a DML statement on the UserTerritory object.

 

Does anyone know of a way to perform a DML operation on the UserTerritory object?  What I want to do is create a testUser record and then assign the testUser to an existing Territory by inserting a UserTerritory record within a unit test.  Is this at all possible?

 

I cannot find a way to do it.

 

Thanks.

Smriti Kumari (Shumpy)Smriti Kumari (Shumpy)
Hello bohemianguy100,

Are you trying to insert Territory2Type and Territory2Model records in Test class ? You don't need to insert records, you can directly query it in test class. It is accessible in test classes.
Eg -  list<Territory2Type> lstterritoryType   = [SELECT id, DeveloperName from Territory2Type where  DeveloperName = 'Territory'];
Note : DML is not allowed for Territory2Type but you can perform DML on Territory2Model.

Eg : Territory2Model terrModel = new Territory2Model(DeveloperName='ModelName', Name='Name');
insert terrModel ;

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

Please mark as best if this helps you.


Thanks,
Smriti