0

I have a testclass that is creates a list of contacts. Line 59:

List<Contact> contacts = [Select Id from Contact limit 1];

I can't figure out why this SOQL query always returns 0 results when I can clearly see contacts in this developer instance.

Here is the execution results in the debug logs:

16:19:09.0 (60381061)|SOQL_EXECUTE_BEGIN|[59]|Aggregations:0|SELECT Id FROM Contact LIMIT 1

16:19:09.0 (64243558)|SOQL_EXECUTE_END|[59]|Rows:0

16:19:09.0 (64273517)|HEAP_ALLOCATE|[59]|Bytes:4

16:19:09.0 (64289880)|HEAP_ALLOCATE|[59]|Bytes:0

16:19:09.0 (64379863)|HEAP_ALLOCATE|[59]|Bytes:4

Is there a permission or configuration I should check for so this query will return a single contact?

3

You have to create your own data.

static testmethod void testContacts()
{
    system.assertEquals(0, [SELECT count() FROM Contact]);
    insert new Contact(/*required fields*/);
    system.assertEquals(1, [SELECT count() FROM Contact]);
}

Isolation of Test Data from Organization Data in Unit Tests

Starting with Apex code saved using Salesforce API version 24.0 and later, test methods don’t have access by default to pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access data that they create. 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
4
  • Thanks for the prompt response! That explains it, however thought of using existing data as a workaround to bypass insertions with validation rules. It's really hard to predict the validation rules where this package will be installed. Would you recommend declaring any required fields in a custom setting object and I can insert test data into those fields for the test class? Perhaps there is a better way to handle insertions where the validation rules will not be consistent. Nov 1 '17 at 21:01
  • @SteveOrgan Are you developing a managed package? Unmanaged? This is the sort of information which would make your question much easier to answer.
    – Adrian Larson
    Nov 1 '17 at 21:04
  • Yes the plan is eventually this would be a managed package. I have classes that would leverage the contactId and callout to an external API. For my test class I originally was inserting test contacts, but in certain test instances the test will fail because of validation rules. Nov 1 '17 at 21:05
  • @SteveOrgan For a managed package, you do not need to worry about failing tests.
    – Adrian Larson
    Nov 1 '17 at 21:06

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.