Plat-Dev-201 practice question 8 of 30

While working in a sandbox, an Apex test fails when run in the Test Runner. However, executing the Apex logic in the Execute Anonymous window succeeds with no exceptions or errors. Why did the method fail in the sandbox test framework but succeed in the Developer Console?

Full set: 204 questions
Answer options
A: The test method does not use system. runAs to execute as a specific user.
B: The test method is calling an @future method.
C: The test method relies on existing data in the sandbox. Correct answer
D: The test method has a syntax error in the code.
Correct Answer:
C. The test method relies on existing data in the sandbox.
Explanation

Apex tests run with data isolation and, by default, do not have access to existing data in the Salesforce organization (a concept known as seeAllData=false). The Execute Anonymous window, however, runs in the current user's context and can access all data they have permission to see. If the code logic depends on pre-existing records, it will succeed in Execute Anonymous but fail in the test context unless the test method first creates the necessary data.

Why Incorrect

A. System.runAs is for testing user permissions and sharing, not for providing data access. The test would still fail if the required data doesn't exist.
B. Calling an @future method requires Test.startTest() and Test.stopTest() but doesn't inherently cause failure if the underlying logic is sound and data is present.
D. A syntax error would prevent the code from being saved or compiled, meaning it could not be run in either the Test Runner or the Execute Anonymous window.

References

- Salesforce Developers, Apex Developer Guide, "Isolation of Test Data from Organization Data in Unit Tests": "By default, Apex tests don’t have access to pre-existing data in the organization... You must create test data."

- Salesforce Developers, Apex Developer Guide, "Executing Anonymous Apex Code": "The code runs as the current user and can fail to compile if the code violates the user's object- and field-level security settings."

Scroll to Top