A developer observes that an Apex test method fails in the Sandbox. To identify the issue, the developer copies the code inside the test method and executes it via the Execute Anonymous tool in the Developer Console. The code then executes with no exceptions or errors. Why did the test method fail in the sandbox and pass in the Developer Console?
A. The test method has a syntax error in the code.
B. The test method relies on existing data in the sandbox.
C. The test method is calling an @future method.
D. The test method does not use System.runAs to execute as a specific user.
B. The test method relies on existing data in the sandbox.
Explanation:
Apex test methods run in an isolated test context, meaning they do not have access to existing org data unless @isTest(SeeAllData=true) is explicitly used.
When the developer copied the test method code into Execute Anonymous, the code ran outside the test execution context, allowing access to existing records in the database. However, during an actual unit test, Salesforce does not allow access to real org data, leading to failures if the test relies on non-test-created records.