+ Start a Discussion
CliffACliffA 

Testing with territories

I need to test some Apex code that will behave differently depending on whether or not the user is assigned to the same territory as the objects they're looking for.

 

I have two classes with the 'with sharing' and 'without sharing' keywords and and they work as expected when testing the code via the UI.  Now I want to write unit tests and I'm running into trouble.  Here's what I'd like to do but can't:

 

  1. Create two territories, one that the user will belong to and one that they won't
  2. Create a new user
  3. Assign the new user to one of the territories by inserting into the UserTerritory object
  4. Create a 2 new accounts and assign one to the user's territory and one to the other territory
  5. Perform tests to ensure everything works as expected

I run into trouble at step 3 - DML is not allowed on this object.

 

I could add "real" data to use for the tests but I'd rather not rely on that for my unit test. 

 

Does anyone have any suggestions on how to best test territory behavior in this scenario?