0

I recently created a test class in which I had a requirement to get Id of a territory that exists in my org. My test class did not had SeeAllData set to true. However I was still able to retrieve the Id of territory using the Territory2 SObject in one of my test methods. I am not really sure how did that happen? Are setup objects accessible in test classes regardless of SeeAllData attribute's value? My sample code looks something like this -

@isTest
public class Test_Something {

    @testSetup
    public static void createTestData(){
        //create test data, I didn't create any territories here.
    }
    @isTest
    static void testSomething(){
        Test.startTest();

        //some custom testing logic

        Territory2 terr=[Select Id from Territory2 where Name='Some_Name'];  
        system.debug('TerritoryId is->' + terr.Id); //Prints correct Value
        Test.stopTest();

        //some assert statements here
    }
}
2

Are setup objects accessible in test classes regardless of SeeAllData attribute's value?

Yes. A wide variety of setup objects are available in test context, as documented here:

However, objects that are used to manage your organization or metadata objects can still be accessed in your tests such as:

  • User
  • Profile
  • Organization
  • AsyncApexJob
  • CronTrigger
  • RecordType
  • ApexClass
  • ApexTrigger
  • ApexComponent
  • ApexPage

This list is not exhaustive.

You need to always code your unit tests defensively when interacting with these setup objects, and be aware that both the record data and record count in these records may change from environment to environment.

This can often bite with batch classes on User, which require great care to ensure their queries don't select more than one batch worth of Users in test classes (which will cause a test failure with an exception). It also often impacts tests that query for specific Users or Profiles.

| improve this answer | |
  • Thank you for the answer David. However I do not see Territory2 sObject in the list of objects that are accessible in test classes. Can you please share some insights? – Ayush Goyal Jan 30 at 17:51
  • Also, what is the secret to almost always find the right documentation link? – Ayush Goyal Jan 30 at 17:52
  • This list is not exhaustive. Most setup objects are available, including Territory2. – David Reed Jan 30 at 17:52
  • and StaticResource – cropredy Jan 31 at 1:56

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.