3

I am new to APEX and ask forgiveness if the answer to my question is obvious, but I can't find a reason for the action that occurs in the Test class versus production and the Developer Console Anonymous window.

The problem is the following code works in the Developer Console and returns the record being requested:

String QuoteNumber = 'CQ-005541';

CanaryAMS__Carrier_Quotes__c UpdateCase = new CanaryAMS__Carrier_Quotes__c();


try {

        UpdateCase =  [SELECT Id, Name, FA_Americo_Notified__c FROM CanaryAMS__Carrier_Quotes__c WHERE Name = :QuoteNumber];

        system.debug('Eureka!');
        system.debug('Americo Quote Record: ' + QuoteNumber);
        system.debug(UpdateCase);

    } catch(QueryException qe) {

        system.debug('QuoteNumber: ' + QuoteNumber);
        system.debug('QueryException: ' + qe.getMessage());
    }

as shown in the following Developer Console screen capture:

enter image description here

However, the following Test class from which the above code was copied:

@isTest
public class Americo_QueryQuoteTest {

    static testMethod void Americo_QueryQuoteTest() {

    String QuoteNumber = 'CQ-005541';

    CanaryAMS__Carrier_Quotes__c UpdateCase = new CanaryAMS__Carrier_Quotes__c();


    try {

            UpdateCase =  [SELECT Id, Name, FA_Americo_Notified__c FROM CanaryAMS__Carrier_Quotes__c WHERE Name = :QuoteNumber];

            system.debug('Eureka!');
            system.debug('Americo Quote Record: ' + QuoteNumber);
            system.debug(UpdateCase);

        } catch(QueryException qe) {

            system.debug('QuoteNumber: ' + QuoteNumber);
            system.debug('QueryException: ' + qe.getMessage());
        }
    }        
}

Fails as shown by the following screen capture:

enter image description here

In both cases the query is attempting to retrieve a live database record. Is there a required permission that must be set to allow a Test class to access a live database record, or are Test classes prohibited from accessing live database records?

7

Test classes by default cannot access real data. It can access only the test data created within the test class. You can read the Understand Test Data article to understand this in detail.

You can either

Create your own test records in your test class and use it for your testing

OR

use See All Data attribute on your test class to access the real data (less recommended option)

The same query is working in Developer Console Anonymous Execution because it can access the existing data in your org.

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.