PDI · Question #43
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 De
The correct answer is B. The test method relies on existing data in the sandbox.. The Apex test method failed in the sandbox but passed in the Developer Console because it relied on existing data that was unavailable in the isolated test execution context.
Question
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?
Options
- AThe test method has a syntax error in the code.
- BThe test method relies on existing data in the sandbox.
- CThe test method is calling an @future method.
- DThe test method does not use System.runAs to execute as a specific user.
How the community answered
(58 responses)- A5% (3)
- B90% (52)
- C2% (1)
- D3% (2)
Why each option
The Apex test method failed in the sandbox but passed in the Developer Console because it relied on existing data that was unavailable in the isolated test execution context.
A syntax error would prevent the code from compiling or executing in both the test method and Execute Anonymous, not just failing in the test method at runtime.
Apex test methods, by default, execute in an isolated context and do not have access to existing organization data. If a test passes in Execute Anonymous (which runs against live data) but fails in a test method, it indicates the test is likely dependent on specific data records or configurations that were present in the sandbox's live data but not explicitly created within the test method itself.
Calling an `@future` method in a test method typically queues it for asynchronous execution and doesn't cause the test to fail if the method logic is sound; it might require `Test.stopTest()` to ensure completion within the test context.
While `System.runAs` is important for testing user permissions and access, its absence would typically lead to failures related to insufficient permissions or incorrect user context, not a data-dependent scenario where it passes in Execute Anonymous.
Concept tested: Apex Test Data Isolation
Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_data_create.htm
Topics
Community Discussion
No community discussion yet for this question.