Courseiva

CCNA Testing, Debugging, and Deployment Questions

59 questions · Testing, Debugging, and Deployment · All types, answers revealed

1
MCQmedium

A developer is preparing a managed package for release and needs to validate that the package's Apex code does not exceed the per-transaction limits enforced by the platform. The developer wants to run the packaged test suite in a scratch org and see the exact number of SOQL queries and DML statements consumed during each test. Which approach best satisfies this requirement?

A.Query the ApexTestResult object with SOQL after the run and read the StackTrace field for each record.
B.Enable debug logs at the FINEST level for the running user and read the cumulative limits as they appear at the bottom of each log.
C.Run the tests with the Salesforce CLI using sf apex run test with the --result-format human flag and inspect the output for limit usage.
D.Run the tests with the Salesforce CLI using sf apex run test with the --result-format json flag and parse the limits object for each test result.
AnswerD

The JSON result format emitted by sf apex run test includes a limits object attached to every test result, exposing counters like SOQL queries and DML statements consumed. Parsing that JSON gives the developer precise, machine-readable per-test limit data, which is exactly what is required to confirm the packaged code stays within platform governor limits before release.

Why this answer

The JSON result format from sf apex run test attaches a limits object to each test result, exposing the exact SOQL and DML counters consumed by every test method. Parsing that structured output gives the developer the precise, per-test governor limit data required to prove a managed package stays within platform limits before release, which the other approaches cannot deliver.

Exam trap

The trap here is assuming that debug logs or human-readable CLI output expose per-test governor limit counters, when only the JSON result payload carries that structured limits data.

2
Multi-Selecthard

A developer is preparing an Apex test class that must cover a service which schedules a Queueable job, and the test must verify that the queued job's logic actually ran and updated a record. The developer also needs the test to pass reliably in a CI pipeline. (Choose two.)

Select 2 answers
A.Use Test.setCreatedDate() to backdate the queued job's enqueue timestamp so the scheduler picks it up immediately.
B.Assert on the updated record after Test.stopTest() returns, since the queued job's DML completes by then.
C.Enqueue the job before Test.startTest() so it is queued outside the limit-reset boundary and runs independently.
D.Wrap the enqueue call in a try/catch for System.AsyncException and treat a caught exception as proof the job executed successfully.
E.Call Test.stopTest() after enqueuing the job so the platform executes the queued job synchronously before assertions run.
AnswersB, E

Once Test.stopTest() returns, all asynchronous transactions spawned during the test have finished, so the database reflects the DML the Queueable job performed. Querying and asserting on the record at that point validates the job's real behavior. This makes the test deterministic and meaningful rather than merely checking that the job was enqueued.

Why this answer

To test Queueable logic, enqueue the job between Test.startTest() and Test.stopTest(); stopTest() forces the asynchronous transaction to complete synchronously, and assertions placed afterward validate the real record changes. This pattern produces deterministic results in CI because the job's effects are observable before the test ends.

Exam trap

The trap here is believing that enqueuing a Queueable job is enough, or that its execution can be detected through exceptions, rather than forcing execution with Test.stopTest() and asserting on resulting data.

3
MCQhard

A developer is preparing to deploy a change set from a sandbox to production. The change set includes an Apex class that references a new custom field on Account. The deployment fails with a 'field does not exist' error. What is the most likely cause and the correct action?

A.The custom field was not added to the change set; the developer must add the field to the change set and redeploy.
B.The custom field is not accessible to the deploying user's profile; the developer must grant field-level security and redeploy.
C.The custom field's API name was changed in the sandbox; the developer must update the Apex class to use the new API name before deploying.
D.The Apex class was deployed before the custom field; the developer must deploy the field first, then the class.
AnswerA

Change sets only include components explicitly added. If the Apex class references a custom field that is not in the change set, the target org will not have that field, causing a compile error. Adding the field to the change set ensures the dependency is deployed. This is a common oversight when deploying code that relies on new metadata, and the error message directly indicates the missing field.

Why this answer

Change sets require all dependent metadata to be included explicitly. When an Apex class references a custom field that is not in the change set, the target org lacks that field, and the deployment fails at compile time. The solution is to add the custom field to the change set and redeploy.

This ensures the field exists before the class is compiled, resolving the dependency error.

Exam trap

The trap here is assuming that deploying the field separately first is necessary, when in fact a change set can include both and deploy them together if the field is added.

4
MCQhard

A developer is debugging an Apex class that is failing in production. The developer wants to capture debug logs for a specific user without affecting other users. Which tool should be used to set up a trace flag for that user?

A.Setup Audit Trail
B.Setup Debug Logs
C.Workbench
D.Developer Console
AnswerB

In Setup, under Debug Logs, you can create trace flags for specific users. This allows you to capture debug logs for that user without affecting others. You can set the log level and expiration. This is the standard way to set trace flags for a user. It meets the requirement precisely.

Why this answer

To capture debug logs for a specific user, a developer should use the Debug Logs page in Setup. There, they can create a trace flag for that user, specifying the log levels and duration. This isolates the logging to that user, avoiding impact on others.

Other tools like Developer Console are for personal debugging, and Audit Trail is for configuration changes.

Exam trap

The trap here is confusing tools like Developer Console or Workbench with the Setup Debug Logs interface, which is the correct place to set trace flags for other users.

5
MCQeasy

A developer has written an Apex class that includes a method to calculate shipping costs. The method contains several conditional branches. The developer wants to ensure that all branches are tested and that the test class provides sufficient coverage for deployment. Which Salesforce feature should the developer use to identify which lines of code are not covered by tests?

A.The Apex Test Coverage report in Salesforce Reports
B.The Apex Test Execution page in Setup
C.The Developer Console's Test > New Run feature
D.The Code Coverage view in the Developer Console
AnswerD

The Code Coverage view in the Developer Console displays a list of classes and their coverage percentages. When you open a class, it highlights covered lines in blue and uncovered lines in red, allowing developers to see exactly which lines lack test coverage. This is the correct tool for identifying uncovered code.

Why this answer

The Code Coverage view in the Developer Console is the correct tool because it provides a visual representation of which lines of code are executed during tests. Uncovered lines are highlighted in red, enabling developers to quickly identify and address gaps in test coverage. This is essential for meeting deployment requirements.

Exam trap

The trap here is confusing overall coverage percentages shown in test results with line-level coverage, which is only available in the Code Coverage view of the Developer Console.

6
MCQeasy

A developer is using the Salesforce CLI to deploy a set of Apex classes and a custom object to a sandbox. The developer wants to validate the deployment without saving any changes to the target org. Which command should the developer use?

A.sf project deploy start --dry-run
B.sf project deploy validate
C.sf project deploy report --status
D.sf project deploy start --check-only
AnswerB

The sf project deploy validate command performs a deployment validation without saving any changes to the target org. It compiles the metadata and runs tests if specified, but does not commit the deployment. This is exactly what the developer needs to check for errors before an actual deployment. It is the correct CLI command for a validation-only deployment.

Why this answer

The Salesforce CLI provides the sf project deploy validate command specifically for validating a deployment without committing changes. It compiles the metadata and runs any specified tests, reporting errors without altering the target org. This is the correct command for a dry-run style validation in the modern Salesforce CLI, ensuring the deployment will succeed before actually deploying.

Exam trap

The trap here is assuming that a --dry-run or --check-only flag exists for sf project deploy start, when validation is actually a separate command.

7
MCQhard

A developer needs to measure the performance of a specific Apex code block in production. Which tool should be used to analyze CPU time without impacting end-user experience?

A.Test.startTest() and Test.stopTest() for profiling.
B.Debug logs with Apex Profiling categories set to 'Finest'.
C.System.debug() statements added throughout the code.
D.The Salesforce Optimizer tool.
AnswerB

Setting the Apex Profiling category to 'Finest' provides granular data on CPU time per method. This is the intended way to profile code performance on the Salesforce platform. It provides the necessary visibility into the execution cost of specific logic blocks, allowing for performance tuning without requiring any production code changes.

Why this answer

The Apex Debug log with profiling enabled is the appropriate tool. By analyzing the 'CPU Time' and 'Total Time' entries, the developer can measure the performance cost of specific method calls. This approach is minimally invasive and can be targeted to specific users, ensuring that performance metrics are gathered in the production environment without causing system-wide impact or performance degradation for the general user base.

Exam trap

Candidates might suggest running anonymous blocks or heavy developer console monitoring in production, which can degrade performance and impact users.

8
MCQmedium

A developer is writing an Apex test method for a service class that makes a callout to an external REST API. The test must not perform the actual callout. The developer creates a static resource containing the JSON response and writes a mock class that implements HttpCalloutMock. Which statement must the developer include in the test method to register the mock before the callout is executed?

A.HttpCalloutMock mock = new MyApiMock(); Test.startTest(); mock.respond(new HttpRequest());
B.Test.setMock(WebServiceMock.class, new MyApiMock());
C.Test.setMock(HttpCalloutMock.class, new MyApiMock());
D.Test.loadData(HttpCalloutMock.SObjectType, 'MyApiMock');
AnswerC

Test.setMock registers the mock implementation for the HttpCalloutMock interface so that any callout made during the test is intercepted and returns the canned response instead of hitting the network. It must be called before the code under test invokes the callout, otherwise the test fails with a callout exception. This is the correct mechanism for isolating Apex callout logic in unit tests.

Why this answer

Test.setMock is the only supported way to inject a mock implementation for HTTP callouts during Apex tests. It must be invoked before the callout is made, typically at the start of the test method. The mock's respond method then supplies the HttpResponse, allowing the developer to test success and error handling without external dependencies.

Exam trap

The trap here is confusing WebServiceMock (for WSDL-based callouts) with HttpCalloutMock (for REST callouts made with HttpRequest).

9
MCQhard

Refer to the exhibit. A developer encounters this LimitException in a bulkified trigger. What is the most likely cause based on the provided stack trace?

A.The trigger is running on a massive dataset, exceeding the total record processing limit of 50,000 records.
B.A SOQL query is being executed inside a 'for' loop that iterates over the Trigger.new collection.
C.The trigger is calling a static method that is performing a DML operation on the same object causing recursion.
D.The system is experiencing temporary resource contention due to excessive concurrent users in the organization.
AnswerB

Performing a SOQL query inside a loop is the primary cause for exceeding the 100-query governor limit. Each iteration triggers a new database request, and after 100 iterations, the transaction terminates. Moving the query outside the loop and utilizing Map-based retrieval is the standard solution.

Why this answer

The LimitException indicating 'Too many SOQL queries' signifies that the code is executing a SOQL query inside a loop. This is a common performance bottleneck in Apex. Proper bulkification requires moving queries outside of loops by gathering IDs into a Set or List, then performing a single query.

Mastering bulkification is essential for passing the PD2 exam and writing scalable enterprise applications.

Exam trap

Candidates often blame the data volume or the complexity of the query, missing the fundamental architectural flaw of placing a query inside a trigger iteration loop.

10
MCQmedium

Refer to the exhibit. A developer encounters this error while performing a bulk update of 200 Account records. What is the root cause of this exception?

A.The trigger logic is attempting to update the same record more than 150 times.
B.The developer is performing individual DML operations inside a loop instead of bulkifying.
C.The batch size in the data loader is set too high for the current trigger logic.
D.The org-wide daily DML limit has been exceeded due to high transaction volume.
AnswerB

Salesforce enforces a strict limit of 150 DML statements per transaction. When a developer places an update statement inside a loop processing 200 records, the limit is exceeded as soon as the 151st iteration occurs. Bulkifying by adding records to a list and performing one DML call is the required fix.

Why this answer

The error indicates that the code is executing DML operations inside a loop rather than performing bulk DML on a collection. In Salesforce, DML operations are limited to 150 per transaction. This is a critical architectural violation because it prevents code from scaling to meet the demands of bulk processing, causing runtime failures during batch updates or heavy user activity, which leads to poor system reliability.

Exam trap

Candidates often mistake this for a record-level validation error or a governor limit related to total records processed, failing to identify that the specific error stems from DML inside a loop.

11
MCQmedium

A developer needs to deploy a new Apex class to production that makes a callout to an external REST service. The callout must be made from a trigger. During testing in a sandbox, the developer writes a test class that performs DML to insert a record that fires the trigger, but the test fails with a 'CalloutException: Methods defined as TestMethod do not support Web service callouts' error. What should the developer do to allow the test to execute the callout successfully?

A.Annotate the test method with @isTest(SeeAllData=true) to allow callouts.
B.Implement the HttpCalloutMock interface and use Test.setMock(HttpCalloutMock.class, new MyCalloutMock()) before the DML operation.
C.Use Test.startTest() and Test.stopTest() around the DML operation to enable callouts.
D.Wrap the callout in a try-catch block and ignore the CalloutException.
AnswerB

Implementing HttpCalloutMock and registering it with Test.setMock allows the test to simulate the external service's response without making an actual callout. This is the correct approach because it satisfies the test's callout requirement while avoiding the restriction against real web service callouts in tests. It also ensures consistent and fast test execution.

Why this answer

The correct solution is to use HttpCalloutMock to simulate the external service. This allows the test to execute the callout logic without violating the platform's restriction on real callouts during tests. It also ensures that the test remains isolated, repeatable, and fast, which is essential for reliable continuous integration.

Exam trap

The trap here is assuming that Test.startTest() or SeeAllData=true can bypass the callout restriction, when actually only mocking the callout with HttpCalloutMock is permitted.

12
Multi-Selectmedium

A developer is deploying a new Lightning web component that calls an Apex controller method. The deployment to production fails because the Apex class is not covered by tests. The developer needs to ensure the Apex class meets the 75% test coverage requirement and that the tests are robust. Which two actions should the developer take to achieve this? (Choose two.)

Select 2 answers
A.Use @TestVisible private methods to expose internal logic for testing without altering the public API.
B.Create test data using Test.loadData() with a static resource to ensure consistent data across test methods.
C.Write test methods that cover all branches of the Apex controller, including positive and negative scenarios.
D.Ensure that the test methods assert expected outcomes and cover exception handling in the controller.
E.Use Test.startTest() and Test.stopTest() to reset governor limits and isolate the test data.
AnswersC, D

Covering all branches ensures that both successful and error paths are tested, which is essential for meeting coverage requirements and validating behavior. It also helps catch edge cases. This is a best practice for Apex testing and directly contributes to robust coverage.

Why this answer

To meet coverage requirements and ensure robust tests, the developer should write test methods that cover all branches, including positive and negative scenarios, and include assertions that validate outcomes and exception handling. These actions ensure that the Apex controller's logic is thoroughly exercised and verified, which is essential for production deployment.

Exam trap

The trap here is focusing on test utilities like Test.loadData() or @TestVisible as primary solutions, when the core requirement is comprehensive test methods with assertions and branch coverage.

13
MCQeasy

Which command is used in the Salesforce CLI to retrieve metadata from an org to a local project?

A.sf project pull
B.sf project retrieve start
C.sf org fetch
D.sf metadata download
AnswerB

This is the primary CLI command to pull metadata from a non-source-tracked org (like a sandbox) into your local project structure. It enables developers to refresh their local code base against the server configuration, ensuring that the local environment accurately reflects the current state of the target org.

Why this answer

The 'sf project retrieve start' command is the standard mechanism for synchronizing metadata from an org to your local development environment. This keeps the local project in sync with the source of truth, enabling developers to work with the latest configuration and code base, which is fundamental to version-controlled development workflows.

Exam trap

Candidates often confuse the retrieve command with the deploy command, or use legacy Force.com CLI syntax instead of the modern 'sf' command structure required for current projects.

14
MCQhard

Refer to the exhibit. A developer encounters this error message while deploying an updated trigger to a production environment. What is the most effective approach to diagnose and resolve this deployment failure?

A.Delete the OrderTrigger from the package manifest file, deploy the remaining components, and reinstall the trigger manually through the Salesforce UI.
B.Increase the Salesforce API version in the package.xml manifest to version 60.0 to bypass legacy execution blocks.
C.Examine the detailed deployment error logs to identify the failing test method or trigger logic, fix the root cause, and re-run validation.
D.Run sf org logout and re-authenticate with the production environment using a different system administrator credential.
AnswerC

Deployment errors wrapping trigger executions usually occur when automated unit tests run during deployment and hit unhandled exceptions. Analyzing the complete stack trace pinpoints the exact line of failure, allowing developers to correct data setup or trigger logic.

Why this answer

Trigger execution failures during deployments typically stem from missing test data or conflicting custom validation rules running against test records. Developers must examine the full stack trace in the debug log or CLI output to identify the exact line causing the exception, ensuring test classes provide comprehensive mock data that satisfies all enterprise automation requirements.

Exam trap

Candidates often attempt to bypass deployment errors by deleting validation rules rather than diagnosing stack traces to identify missing test data.

15
Multi-Selectmedium

Which TWO statements are true regarding the use of 'System.debug()' in a production environment?

Select 2 answers
A.They have no performance impact on the execution time of the transaction.
B.They can expose sensitive information if not properly filtered.
C.They should always be left in the code to assist with future support cases.
D.They count against the overall log file size limits.
E.They are automatically stripped by the Salesforce compiler in production.
AnswersB, D

Debug statements are often written during development without considering security implications. If they log record contents that include PII or sensitive business data, those logs become a security risk when stored in Salesforce. Proper code reviews must ensure that no debug statements log sensitive information before being committed to production.

Why this answer

System.debug() statements are generally discouraged in production because they consume log space and can inadvertently expose sensitive data. While they are useful for debugging, they should be removed or wrapped in conditional logic. Efficient log management is vital for maintaining high performance and ensuring that production environment overhead remains minimal during peak business hours and critical transactional windows.

Exam trap

Candidates often assume System.debug statements are harmless in production, failing to realize they count against log file size limits and potentially expose sensitive data to unauthorized users.

16
Multi-Selecthard

A developer must write Apex tests that reliably cover a Queueable class which performs a callout and then enqueues a second Queueable job. The tests must not make real external callouts. (Choose two.)

Select 2 answers
A.Annotate the test method with @IsTest(SeeAllData=true) so the chained job can see the records it needs.
B.Set the Queueable to run with System.enqueueJob(new MyQueueable(), 5) to increase the delay so the test can observe intermediate state.
C.Replace the callout with a hard-coded response inside the Queueable when Test.isRunningTest() returns true.
D.Implement HttpCalloutMock and register it with Test.setMock(HttpCalloutMock.class, mock) before invoking the Queueable.
E.Call Test.startTest() before enqueueing the job and Test.stopTest() after, so the asynchronous work executes synchronously.
AnswersD, E

Registering an HttpCalloutMock replaces the real HTTP transport with the mock during the test, so the Queueable's callout returns the stubbed response without leaving the Salesforce servers. This is the standard mechanism for testing callout logic offline and keeps the test deterministic and fast.

Why this answer

To test a Queueable that makes a callout and chains another job without real external calls, the developer registers an HttpCalloutMock so the callout is stubbed, and wraps the enqueue in Test.startTest()/Test.stopTest() so queued work runs synchronously. Together these techniques validate both the callout handling and the chained job's behavior in a controlled, offline test.

Exam trap

The trap here is believing that Test.isRunningTest() branching is the proper way to avoid callouts, when mocking the HTTP transport is the supported technique.

17
MCQhard

A developer is troubleshooting a production issue where a trigger occasionally exceeds CPU time limits. The developer wants to capture detailed debug logs for a specific user without slowing down the entire org, and then analyze the log to identify the slowest operations. Which combination of Salesforce tools should the developer use?

A.Debug Logs with a user-specific trace flag, then the Analysis perspective in the Developer Console
B.Event Monitoring via the EventLogFile object, then Workbench to query the logs
C.Setup Audit Trail to identify the user, then Apex Replay Debugger to step through the log
D.Apex Profiler in VS Code with the Apex extension, then the Timeline view
AnswerA

Creating a trace flag for the specific user captures debug logs only for that user's transactions, avoiding org-wide overhead. The Analysis perspective in the Developer Console parses the log and highlights the slowest operations, such as SOQL queries, DML statements, and method calls, by execution time. Together they let the developer isolate and diagnose the CPU time issue efficiently.

Why this answer

A user-specific trace flag generates debug logs only for that user, keeping overhead contained while capturing the problematic transaction. The Developer Console's Analysis perspective then parses the log and ranks operations by execution time, exposing the slowest SOQL, DML, and method calls. This focused capture and analysis directly targets the CPU time issue without impacting other users.

Exam trap

The trap here is reaching for Event Monitoring or configuration audit tools, which capture security and setup events rather than the line-level Apex execution timing needed to find a CPU bottleneck.

18
MCQeasy

A developer is creating a custom exception to handle business logic errors. What is the correct way to declare this exception so it can be caught specifically in a try-catch block?

A.public class MyException implements Exception {}
B.public class MyException extends Exception {}
C.public exception MyException {}
D.public static exception MyException = new Exception();
AnswerB

Extending the base Exception class is the correct way to create a custom exception in Apex. This allows the class to inherit all core exception functionality, including tracking the stack trace and message strings, while enabling specific catch blocks that can handle these errors distinctly from system-level platform exceptions.

Why this answer

Defining a custom exception class extending the built-in 'Exception' class is the standard practice in Apex. This allows developers to catch specific business errors separately from system errors like NullPointerExceptions. Proper exception handling is critical for maintaining clean, readable code and ensuring that users receive meaningful feedback when operations fail during complex business processes or integration calls.

Exam trap

Candidates often mistakenly believe custom exceptions must extend 'System.Exception' or 'ApexException' rather than the standard 'Exception' class, which is the actual base class for all custom exceptions in Apex.

19
MCQmedium

A developer needs to debug an Apex trigger that intermittently fails in production with a 'UNABLE_TO_LOCK_ROW' error when multiple users update related records. Which technique should the developer use to capture the detailed execution context and identify the conflicting transaction?

A.Run the Apex Test Execution with 'Always Run Asynchronously' enabled to simulate concurrent updates.
B.Enable debug logs for the triggering user and analyze the log for the row lock error and preceding DML operations.
C.Set up a custom logging object and insert a record at the start of each trigger invocation to track user activity.
D.Use the Developer Console's Query Plan tool to analyze the selectivity of the SOQL queries in the trigger.
AnswerB

Debug logs capture the sequence of DML operations, SOQL queries, and exceptions. By setting a debug log for the user who encounters the error, the developer can see which records were locked and by which operation. The log will show the DML statement that caused the lock and the preceding operations, helping identify the conflicting transaction. This is the most direct way to diagnose row lock issues in production.

Why this answer

Debug logs are the primary tool for diagnosing runtime errors like UNABLE_TO_LOCK_ROW. They record the exact DML operations and the order in which they occurred, including the records involved. By enabling a debug log for the affected user, the developer can see which DML statement failed to acquire a lock and what operations preceded it.

This information is critical to identify the conflicting transaction and refactor the code to avoid locking contention.

Exam trap

The trap here is assuming that query optimization tools or custom logging can reveal row lock conflicts, when only debug logs capture the necessary DML sequence and lock error details.

20
MCQmedium

A developer is writing an Apex test class for a service that must be resilient against partial failures. The service calls a REST endpoint using a callout and, when the callout succeeds, performs a DML update on a set of Account records. The developer wants the test to simulate the HTTP response without hitting the real external system. Which approach should the developer use?

A.Create the mock response by inserting a ContentVersion record and reference it from the callout using the endpoint URL of the mock.
B.Implement the HttpCalloutMock interface and register it with Test.setMock(HttpCalloutMock.class, new MyMock()) before the callout is invoked.
C.Annotate the test method with @IsTest(SeeAllData=true) so the test can reach the live endpoint and then assert on the returned payload.
D.Wrap the callout in Test.startTest() and Test.stopTest() so the platform automatically intercepts the outbound request and returns a synthetic 200 response.
AnswerB

Registering a mock that implements HttpCalloutMock through Test.setMock causes the Apex runtime to return the canned HttpResponse instead of performing a real HTTP transaction, so the test never touches the external service and remains deterministic. This is the supported mechanism for isolating callout logic in Apex tests and works regardless of whether the code under test uses Http or HttpRequest directly.

Why this answer

The Apex testing framework provides Test.setMock with an HttpCalloutMock implementation precisely so callouts can be exercised without external dependencies. Registering the mock before the request executes makes the runtime substitute the developer-defined HttpResponse, letting assertions validate both the request built by the code and the handling of the response, including error status codes.

Exam trap

The trap here is assuming Test.startTest() and Test.stopTest() somehow intercept or simulate web service callouts, when they only reset limits and flush asynchronous work.

21
MCQmedium

What is the best way to test asynchronous Apex (Future methods, Queueable) to ensure the logic within the background job actually executes?

A.Use System.enqueueJob() inside the test method.
B.Call the future method directly in the test.
C.Wrap the test logic in Test.startTest() and Test.stopTest().
D.Use a Thread.sleep() command to wait for the job.
AnswerC

Test.startTest() and Test.stopTest() are essential for testing asynchronous processes. When stopTest() is called, Salesforce forces the execution of all asynchronous jobs created since startTest(). This allows developers to verify data changes and logic execution immediately after the stopTest() call, ensuring robust unit test coverage for background processes.

Why this answer

Using Test.startTest() and Test.stopTest() is the only supported way to force asynchronous code to execute synchronously within a test block. Any asynchronous jobs added between these two calls are processed when stopTest() is invoked. This pattern ensures that tests can assert the outcome of background operations, which is crucial for testing complex integrations or batch processes that rely on asynchronous execution.

Exam trap

Candidates incorrectly assume that asynchronous methods will execute automatically in a test, forgetting that they must explicitly trigger the execution using Test.startTest() and Test.stopTest().

22
MCQhard

Refer to the exhibit. A developer encounters a 'Maximum stack depth reached' error. What is the most likely cause of this recursive error?

A.The code is using a SOQL query inside a loop, exceeding the limit.
B.The trigger logic performs a DML operation that causes the same trigger to fire again.
C.The trigger is processing too many records in a single batch, exceeding 200.
D.The code is attempting to access a field that does not exist in the current scope.
AnswerB

When an Apex trigger executes DML on the same object that triggered it, it causes the trigger to re-enter its own execution block. Without a static control variable to stop this recursion, the trigger fires infinitely until it hits the stack depth limit, which is exactly what the error message indicates.

Why this answer

This error indicates infinite recursion, where a trigger fires, updates a record, and that update triggers the same logic again. The stack trace shows the method calling itself. This is a common issue in Salesforce triggers and must be handled using static boolean flags or check variables to ensure that logic only executes once per transaction, preventing circular loops that exhaust system resources.

Exam trap

Many candidates incorrectly attribute this error to infinite loops in logic rather than the specific Salesforce trigger recursion caused by DML operations within the same trigger context.

23
MCQhard

A developer is deploying a new Apex class to production using a change set. The class contains a method that performs a callout to an external web service. During deployment, the developer receives an error: 'Callout not allowed from a test method.' Which action should the developer take to resolve this error while ensuring the test method still validates the callout logic?

A.Use Test.isRunningTest to conditionally skip the callout when the test is executing.
B.Implement the HttpCalloutMock interface and use Test.setMock to simulate the callout response in the test method.
C.Move the callout logic to a future method and call it from the test method.
D.Wrap the callout in a try-catch block to suppress the error during test execution.
AnswerB

Implementing HttpCalloutMock and using Test.setMock allows the test method to simulate the external callout without actually making a network request. This satisfies the requirement that test methods cannot perform callouts, while still validating that the code correctly handles the response. It is the standard Salesforce approach for testing callouts.

Why this answer

The correct solution is to implement HttpCalloutMock and use Test.setMock, which allows the test to simulate the callout response without making a real callout. This adheres to Salesforce's testing requirements and ensures the callout logic is properly validated. Other options either do not resolve the error or compromise test coverage.

Exam trap

The trap here is thinking that try-catch or conditional skipping is a valid workaround, but the platform enforces the restriction before any code executes, and skipping reduces test effectiveness.

24
Multi-Selectmedium

A developer is writing a test class for a service that makes callouts to an external web service. The test method needs to simulate the callout response without making an actual HTTP request. (Choose two.)

Select 2 answers
A.Implement the HttpCalloutMock interface and use Test.setMock(HttpCalloutMock.class, mock).
B.Use @isTest(SeeAllData=true) to access external data.
C.Use Test.startTest() and Test.stopTest() to isolate the callout.
D.Set the callout to run asynchronously to avoid the callout limit.
E.Use Test.setMock(WebServiceMock.class, mock) with a WebServiceMock implementation.
AnswersA, E

Implementing HttpCalloutMock allows you to define a fake response. Test.setMock registers the mock for the test, so callouts are intercepted. This is the standard way to test callouts. It ensures no actual HTTP request is made and the response is controlled. This is a correct technique.

Why this answer

To simulate callouts in Apex tests, developers can use HttpCalloutMock for HTTP callouts or WebServiceMock for SOAP callouts. Both require implementing the respective interface and registering the mock with Test.setMock. This intercepts the callout and returns a controlled response.

Test.startTest and Test.stopTest do not simulate callouts, and SeeAllData does not affect callouts.

Exam trap

The trap here is assuming that Test.startTest or SeeAllData can simulate callouts, when only mock interfaces can intercept callouts.

25
MCQmedium

A developer is writing an Apex class that needs to handle high volumes of data. Which pattern should they follow to avoid hitting Governor Limits?

A.Use @future methods for every DML operation.
B.Refactor all SOQL queries and DML statements outside of loops.
C.Enable 'Parallel Apex Testing' in the org setup.
D.Increase the record limit by using the Apex 'Limits' class.
AnswerB

This is the definition of bulkification. By collecting all IDs to query or all records to update into a collection before the loop, the developer reduces the number of calls to the database to a single query/update. This pattern is the single most important factor in avoiding governor limit exceptions.

Why this answer

Bulkification is the cornerstone of Salesforce development. By processing records in collections (Lists, Maps, Sets) rather than iterating and performing DML or SOQL inside loops, developers keep their code within platform limits. This ensures the code can handle the maximum number of records in a single transaction, which is crucial for scalability and performance in high-volume enterprise applications.

Exam trap

Candidates sometimes try to solve governor limits by adding try-catch blocks or reducing batch sizes manually instead of restructuring the loops.

26
MCQmedium

A developer is preparing to deploy a change set from a sandbox to production. The change set includes a new custom object, its fields, a Visualforce page, and an Apex controller. After uploading the change set, the developer notices that the custom object and fields are missing from the change set components. What is the most likely reason?

A.The change set was created in a sandbox that is not the source of the custom object and fields.
B.The custom object and fields were not explicitly added to the change set when it was created.
C.The custom object and fields are only available in the sandbox and cannot be deployed to production.
D.The custom object and fields were not added to the change set because they are not supported in change sets.
AnswerB

Change sets require manual selection of components. Even if the custom object and fields are referenced by other components, they are not automatically included. The developer must add them individually. This is the most likely reason they are missing. The other components (Visualforce page, Apex controller) were added, but the object and fields were overlooked.

Why this answer

Change sets do not automatically include dependencies. When a developer adds a Visualforce page or Apex class, the associated custom object and fields are not added automatically. The developer must manually add each component.

Therefore, the missing object and fields are due to them not being explicitly added during change set creation.

Exam trap

The trap here is assuming that change sets automatically include dependent components like custom objects and fields when related components are added.

27
MCQmedium

A developer is writing an Apex test class for a service that calls an external REST endpoint via a callout. The test must verify the parsing logic without hitting the external system, and it must also assert that the service throws a custom exception when the endpoint returns a 500 status. Which combination of techniques is required?

A.Use HttpCalloutMock to return a 200 response for the happy path, and use Test.setMock with a separate mock returning a 500 response to assert the exception.
B.Use a WebServiceMock implementation, since WebServiceMock is the only interface that supports simulating HTTP responses in tests.
C.Use Test.setMock with HttpCalloutMock and set the mock's response status to 500 for both the happy path and the error path.
D.Use Test.isRunningTest within the service to branch around the callout logic and return hardcoded values.
AnswerA

Apex forbids real callouts during tests, so Test.setMock with an implementation of HttpCalloutMock supplies a synthetic HttpResponse. One mock instance returning status 200 exercises the parsing path, and a second mock returning status 500 exercises the error branch so the custom exception can be asserted. Both paths are covered without any external network access, which is exactly the required combination.

Why this answer

Tests cannot perform real callouts, so HttpCalloutMock injected via Test.setMock supplies a controllable HttpResponse. Using one mock that returns status 200 exercises the parsing logic, while a second mock returning status 500 drives the error branch so the custom exception can be asserted, covering both paths with no external dependency.

Exam trap

The trap here is reaching for Test.isRunningTest to skip the callout, which bypasses the very parsing code the test is meant to verify.

28
MCQmedium

During a deployment, a developer notices that existing Apex tests are failing, even though the new code changes are unrelated to the failing tests. What is the most likely cause?

A.The deployment package deleted existing tests that were required for coverage.
B.The tests depend on existing data in the environment that has changed.
C.The Salesforce platform automatically updates existing Apex code, causing regressions.
D.Deployment always triggers a full system reset of the production database.
AnswerB

Tests that query existing data rather than creating their own data are prone to failure if that data changes. This violates best practices for test development. Reliable tests must be self-contained, creating their own data in the @testSetup method to ensure consistency regardless of the environment's state.

Why this answer

This scenario suggests that existing tests are dependent on specific org data or state that was altered, or they are fragile due to hardcoded dependencies. Salesforce tests must be independent and self-contained to avoid such side effects. This highlights the critical importance of test data isolation and the avoidance of relying on existing production records, which are unreliable for consistent testing and can lead to unexpected failures during deployment.

Exam trap

Candidates often assume deployment failures are due to compiler errors in new code, ignoring runtime failures caused by brittle dependencies on pre-existing org data.

29
MCQmedium

A developer is writing a test class that requires a user with a specific profile. How should the developer handle the user creation process?

A.Query an existing user from the production environment.
B.Create a new user within the test method and use System.runAs().
C.Hardcode the username of a system administrator.
D.Grant the test user the 'Modify All Data' permission via a PermissionSet.
AnswerB

Creating a new user ensures the test is self-contained. Using System.runAs() allows the test to execute as that specific user, which is necessary to test code that relies on user permissions, record sharing, or profile-specific logic, ensuring the code behaves correctly under the expected security context for end users.

Why this answer

Tests must create their own data, including Users, to ensure they remain self-contained and environment-independent. Using the 'RunAs' method in combination with user creation allows the developer to simulate specific security and permission contexts. This ensures that the logic is tested exactly as it would be for the target user, confirming that the code respects the platform's security model consistently.

Exam trap

Candidates often assume they can use existing users from the org or rely on the running user, forgetting that tests must be isolated and explicitly define their security context.

30
MCQhard

Refer to the exhibit. A developer encounters this error during a unit test. What is the most likely cause, and how should it be resolved?

A.The test class needs more setup data, so add more records.
B.The trigger logic is missing a bulkified query pattern.
C.Increase the SOQL limit by modifying the Org settings.
D.Change the test class to run as a user with fewer permissions.
AnswerB

The error indicates that the code is executing queries inside a loop, which is a classic non-bulkified anti-pattern. By refactoring to collect IDs into a collection and executing one query before the loop, the developer reduces the total SOQL count to one, staying well under the 100-query limit.

Why this answer

The 101 SOQL limit is triggered when a loop performs a query for every record in a collection. Developers should refactor code to move queries outside of loops by collecting IDs into a set and performing a single, bulkified SOQL query. This pattern is fundamental to Salesforce development, ensuring that applications remain performant and scalable regardless of the volume of data processed during transactions.

Exam trap

Candidates often focus on the specific SOQL error rather than recognizing the underlying architectural failure of non-bulkified code, which is the root cause in almost all trigger scenarios.

31
Multi-Selecthard

A developer is writing an Apex test class for a controller that uses a Visualforce page with a standard controller. The test must cover pagination logic that relies on the StandardSetController. Which TWO actions should the developer take to ensure the test is reliable and covers the pagination behavior? (Choose two.)

Select 2 answers
A.Set the page size to a large number so that all test records fit on one page, simplifying the test and avoiding pagination complexities.
B.Use Test.setCurrentPage() to set the Visualforce page context and then instantiate the StandardSetController with a query locator.
C.Use Test.startTest() and Test.stopTest() to isolate the pagination logic and reset governor limits between pages.
D.Use Test.isRunningTest() in the controller to bypass the query and return a hardcoded list of records for pagination testing.
E.Create test data that exceeds the page size to force multiple pages, and then invoke the pagination methods such as next() and previous().
AnswersB, E

StandardSetController is typically instantiated in a controller extension, and its behavior can depend on the Visualforce page context. Using Test.setCurrentPage() sets the page reference, and then the test can instantiate the StandardSetController with a query locator to simulate the controller's data set. This ensures the pagination methods operate on the expected data and page context, making the test more realistic and reliable.

Why this answer

To reliably test pagination with StandardSetController, the test must create enough records to span multiple pages and then invoke the pagination methods. Additionally, setting the Visualforce page context with Test.setCurrentPage() and instantiating the StandardSetController with a query locator ensures the controller operates as it would in a real page. These two actions together exercise the pagination logic and verify the expected behavior across pages.

Exam trap

The trap here is assuming that isolating limits or bypassing queries simplifies pagination testing, when in fact pagination requires multiple pages of real data and a proper page context.

32
MCQmedium

A developer is troubleshooting an Apex class that intermittently throws a System.LimitException during integration tests. The developer needs to see the exact sequence of method calls and the values of variables at each step without modifying the class. Which Salesforce feature should the developer use?

A.The Apex Test Execution page in Setup
B.Checkpoints in the Developer Console
C.Apex Replay Debugger
D.Debug Log levels set to FINEST for Apex Code
AnswerC

Apex Replay Debugger lets a developer download a debug log from the org and step through the execution line by line, inspecting variable values and the call stack without editing the class. It reproduces the exact run that produced the log, which is ideal for diagnosing an intermittent limit exception during integration tests.

Why this answer

Apex Replay Debugger consumes a captured debug log and replays execution with breakpoints, variable inspection, and call-stack navigation, all without altering the class. Because the failure is intermittent and occurs during integration tests, the developer can capture a log of the failing run and replay it to find the exact point where the limit is exceeded.

Exam trap

The trap here is equating detailed debug log levels with interactive step-through debugging, which only the replay tool provides.

33
MCQhard

A developer is preparing a deployment of a new Apex class and its test class to production. The test class uses @TestSetup to insert 200 Account records, and each of six test methods queries all 200 Accounts. The deployment fails during validation with a CPU timeout error. Which change most directly addresses the timeout without reducing coverage?

A.Move the Account insertion into each test method instead of @TestSetup so each method gets a fresh set of records.
B.Annotate the test class with @isTest(OnInstall=false) to defer test execution until after the package is installed.
C.Convert the test methods to use System.runAs() so the queries execute under a user with fewer permission checks.
D.Replace the full-object queries with selective SOQL that filters and returns only the fields and rows each test actually needs.
AnswerD

CPU time in tests is dominated by query processing, and selecting all 200 rows with every field across six methods multiplies that cost. Filtering rows and projecting only required fields reduces the rows and columns the query engine must materialize, lowering CPU consumption while still exercising the same logic. Coverage is preserved because each test still validates the behavior it targets.

Why this answer

CPU timeouts in test execution usually trace to expensive query volume. Querying every row with every field six times forces the platform to materialize a large result set repeatedly. Tightening the SOQL so each test retrieves only the fields and rows it needs cuts CPU consumption directly while keeping the same behavioral assertions and coverage.

Exam trap

The trap here is treating a CPU timeout as a setup-data problem and moving inserts around, when the dominant cost is the repeated broad query in each test method.

34
MCQeasy

A developer needs to give a CI service account the ability to run the Apex test suite in a production org without interactive login, and the pipeline must not store a user's personal password. Which authentication approach should the developer configure?

A.Authenticate the CI job with a connected app using the JWT bearer flow and authorize the integration user in advance.
B.Store the integration user's username and password in an encrypted pipeline variable and authenticate with sf org login web.
C.Use the SOAP login call with the integration user's credentials and a security token appended to the password.
D.Generate a personal access token in the org's setup and pass it to the CLI with the sf org login access-token command.
AnswerA

The JWT bearer flow lets a CI service authenticate as a pre-authorized integration user using a signed certificate, with no interactive login and no stored user password. The user must be authorized once in the org, after which the pipeline can request access tokens unattended. This is the standard, secure approach for headless pipeline authentication to run Apex tests in production.

Why this answer

The JWT bearer flow with a connected app and a pre-authorized integration user provides headless, passwordless authentication for CI, since the pipeline signs a JWT with a certificate instead of storing user credentials. This satisfies the requirement to run Apex tests in production without interactive login or a personal password.

Exam trap

The trap here is assuming an encrypted password variable or a personal access token is acceptable for CI, when passwordless certificate-based authentication is the supported secure path.

35
MCQeasy

A developer wants to log information to the Debug Log for a specific class only, without cluttering the logs for the entire organization. What is the most efficient way to achieve this?

A.Set the organization-wide debug log level to 'FINEST'.
B.Use the Debug Logs Setup page to create a Trace Flag for the user/class.
C.Hardcode log level changes in the Apex class constructor.
D.Use 'System.setLogLevel()' in the Apex code.
AnswerB

Trace Flags allow developers to define precise logging levels for specific users, classes, or triggers. This is the official and most efficient way to capture debug information while keeping log output relevant and minimized, which is essential for maintaining a clean and performant development environment for the entire team.

Why this answer

Setting a 'Trace Flag' for a specific user or class is the standard Salesforce tool for targeted logging. This allows developers to isolate log output to their specific testing or debugging activities, preventing the organization's overall log capacity from being consumed by irrelevant system-wide logs. It is a fundamental skill for keeping production and sandbox environments manageable during active development and troubleshooting phases.

Exam trap

Candidates often suggest changing the logging level for the entire organization, which is inefficient and impacts performance, instead of using the targeted Trace Flag feature.

36
MCQhard

Refer to the exhibit. A developer encounters this policy during a deployment attempt via the CI/CD pipeline. What does this indicate about the deployment process?

A.The developer needs to increase the CI/CD pipeline timeout.
B.The deployment is being blocked by a governance policy.
C.The source code has syntax errors preventing the deployment.
D.The Salesforce org is currently in read-only mode.
AnswerB

The JSON output is a clear indicator that a security policy is actively blocking the action. The 'deny_all' policy ensures that no direct deployments are permitted to production, forcing developers to follow a secure, compliant path such as a pull request process or a release manager approval.

Why this answer

The JSON policy indicates that the environment is locked against direct deployment actions, likely as a security measure to prevent unauthorized changes. This requires the developer to use a standard release path, such as moving code through a staging environment or obtaining specific approvals. Understanding these governance policies is crucial for maintaining compliance and security in large-scale enterprise deployments.

Exam trap

Exam candidates often misinterpret deployment governance policies as syntax bugs or expired user credentials rather than pipeline rules.

37
MCQhard

A developer is preparing to deploy a complex change set from a sandbox to production. The change set includes Apex classes, Visualforce pages, and a new custom object. The developer runs all tests in the sandbox and achieves 100% coverage, but the deployment to production fails with the error: 'Your organization's code coverage is 68%. You need at least 75% coverage to complete this deployment.' What is the most likely cause of this discrepancy?

A.The production org has a higher number of asynchronous Apex jobs that interfere with test execution.
B.The production org has existing Apex classes that are not covered by the tests in the change set, lowering the overall coverage.
C.The sandbox and production have different API versions, causing the tests to run differently.
D.The change set does not include the test classes, so they are not run in production.
AnswerB

Salesforce calculates code coverage org-wide for deployments. If production already contains Apex classes that are not fully covered by the tests being deployed, the overall coverage can fall below 75%, even if the new code has 100% coverage. The developer must ensure that tests cover existing code as well, or include additional tests in the change set to raise overall coverage.

Why this answer

The deployment failed because Salesforce requires 75% overall code coverage across the entire organization, not just the new code. Production likely contains legacy Apex classes that are not covered by the tests in the change set. To resolve this, the developer must include tests that cover those existing classes or ensure that the deployed tests exercise them.

Exam trap

The trap here is assuming that 100% coverage in the sandbox guarantees successful deployment, when actually production's existing code must also be covered to meet the org-wide 75% threshold.

38
MCQmedium

A developer is writing an Apex test class for a service that calls an external REST API using a Named Credential. The test must not make real callouts, and the developer wants to verify that the correct endpoint and body are sent. Which approach should the developer use?

A.Use Test.isRunningTest() inside the service class to conditionally skip the callout and return a hardcoded response.
B.Wrap the callout in Test.startTest() and Test.stopTest() to prevent the callout from executing during the test.
C.Set the endpoint in a Custom Setting and use a test-specific value that points to a local mock server.
D.Implement the HttpCalloutMock interface in a test class and register it with Test.setMock(HttpCalloutMock.class, new MockImpl()).
AnswerD

Implementing HttpCalloutMock and registering it via Test.setMock replaces the real callout with the mock's respond() method. This allows the test to assert that the request was constructed correctly and to return a canned response. It is the standard Salesforce-recommended way to test callout logic without hitting external services, and it works with Named Credentials because the mock intercepts the Http.send() call.

Why this answer

The HttpCalloutMock interface is the designated mechanism for simulating callouts in Apex tests. By implementing it and registering an instance with Test.setMock, the developer can intercept Http.send() calls, return a controlled response, and inspect the HttpRequest to confirm the endpoint and body. This keeps the test isolated, fast, and free of external dependencies, and it aligns with Salesforce best practices for testing callout logic.

Exam trap

The trap here is assuming that Test.startTest() or Test.isRunningTest() can suppress or bypass a callout, when in fact only a registered HttpCalloutMock prevents the real callout.

39
MCQmedium

Which of the following is an advantage of using a 'Source-Driven' development model over an 'Org-Centric' model?

A.It allows developers to skip unit tests during the release process.
B.It eliminates the need for managing deployment manifests.
C.It facilitates parallel development through version control branching.
D.It allows for faster development because you don't have to compile code.
AnswerC

Branching allows multiple developers to work on different features simultaneously without interfering with each other's code. This is a core benefit of source-driven development, as it allows for clean integration, easier code reviews, and a clear history of changes that can be rolled back if necessary.

Why this answer

Source-driven development treats the version control system as the source of truth, enabling better collaboration, easier branching, and more stable release cycles. It removes the dependency on the state of a single, monolithic org. This approach is essential for large teams and modern DevOps, reducing the risks associated with manual configuration changes and providing a clear, auditable history of the entire application's development.

Exam trap

Test-takers frequently mistake source-driven development for simple backup strategies rather than recognizing its core strength in facilitating version control branching and parallel collaboration.

40
MCQeasy

A developer wants to inspect private variable states and trace execution paths of a complex trigger framework during a sandbox debugging session. Which tool should the developer use to capture this diagnostic information?

A.Salesforce Setup Audit Trail
B.Salesforce Developer Console Log Inspector
C.Salesforce Event Monitoring Analytics
D.Salesforce Optimizer Report
AnswerB

The Log Inspector provides detailed hierarchical views of execution logs, heap sizes, and database events. It allows developers to step through checkpoints and analyze memory usage, making it the primary built-in utility for deep Apex debugging.

Why this answer

The Developer Console includes a powerful execution log inspector and perspective layout specifically designed for tracing Apex transactions. Debug logs record database queries, heap allocations, and method entries, enabling developers to isolate root causes of unexpected runtime behaviors efficiently during active troubleshooting sessions.

Exam trap

Candidates often confuse setup audit trails or general logging tools with the Developer Console, failing to recognize that the Log Inspector is specifically engineered for real-time transaction debugging.

41
Multi-Selectmedium

A developer is preparing for a deployment using Salesforce DX. Which TWO practices are recommended to ensure successful and repeatable deployments?

Select 2 answers
A.Maintain the entire org metadata in a single, unversioned folder.
B.Use Scratch Orgs to develop and test features in isolation.
C.Manually deploy components via the Change Set UI for every release.
D.Utilize Git to manage source code and configuration changes.
E.Avoid using unit tests to save time during deployment cycles.
AnswersB, D

Scratch orgs provide ephemeral, configurable environments that ensure developers are working against a baseline that matches the project's source. This isolation prevents configuration conflicts and ensures that all dependencies are explicitly defined, leading to higher quality deployments and fewer missing components during the actual release process.

Why this answer

Using source-driven development with Salesforce DX allows teams to maintain a version-controlled repository as the source of truth. By utilizing Scratch Orgs for development and testing, developers ensure that the environment is clean and reflects the current state of metadata. These practices minimize 'org drift' and ensure that deployments are predictable, reproducible, and easily traceable through version control history, which is crucial for professional release management.

Exam trap

Candidates often prioritize manual change sets or simple deployments, failing to understand that modern Salesforce DX relies on source-driven development using Git as the source of truth.

42
MCQhard

A developer is debugging why a trigger fires twice for a single record save in a sandbox. The trigger is defined on Account with `before insert, after insert` and the class uses a static Boolean guard variable to prevent recursion. Logs show two separate transactions. Which explanation best fits this behavior?

A.The developer should add `with sharing` to the trigger to prevent the second execution.
B.The static Boolean guard is reset between the before and after phases of the same transaction, allowing the logic to run again.
C.A second DML operation on the same Account was performed by another process, such as a workflow field update or a related-record trigger, producing a distinct transaction.
D.The trigger was deployed twice, so the platform executes both copies for every save.
AnswerC

Two separate transactions indicate the record was saved more than once. A workflow field update re-saves the record and fires the trigger again in a new execution context, and a trigger on a related object performing DML on the Account would do the same. Static guards cannot span transactions, so they cannot prevent this second firing.

Why this answer

Static variables live only for one transaction, so a guard cannot stop a trigger from firing again when the same record is saved in a new transaction. Workflow field updates, process-driven updates, or DML from a related object's trigger each create a new context, which is why the logs show two distinct transactions and the trigger runs twice.

Exam trap

The trap here is relying on a static Boolean guard to prevent all re-entry, when a guard cannot cross transaction boundaries created by workflow field updates or related DML.

43
MCQhard

A developer deploys metadata to a production org using the Salesforce CLI. The deployment succeeds, but a post-deployment validation script that relies on a newly created custom setting record fails because the record is missing. The developer confirms the custom setting metadata was included in the package. What is the most likely explanation?

A.Custom setting records are not deployable through Metadata API, so they must be inserted with Apex or the data loader after deployment.
B.The deployment ran with the --dry-run flag, which validates but does not commit custom setting records to the target org.
C.Custom setting records deploy only when the org has the Custom Settings license enabled on the target user's profile.
D.The post-deployment script ran before the custom setting metadata finished indexing, so the record existed but was not yet queryable.
AnswerA

Custom setting records are data, not metadata, in the Metadata API sense. Although the custom setting object definition deploys with the package, its individual records are not carried by the deployment. A post-deploy script that expects a pre-populated record will therefore fail until the record is inserted separately via Apex, Anonymous Apex, or the data loader.

Why this answer

Custom setting records are treated as data rather than metadata, so a deployment that includes the custom setting definition does not carry its records. The post-deploy script fails because it queries a record that was never inserted into production. The developer must load the record separately after the metadata deployment completes, typically through Anonymous Apex or the data loader.

Exam trap

The trap here is assuming that because custom setting metadata deployed successfully, its records were deployed too.

44
MCQmedium

A developer is attempting to debug a failed deployment in a sandbox. The error message is cryptic, and the debug logs are not capturing the expected execution flow. What should the developer do first?

A.Delete the Apex class and re-deploy it.
B.Increase the debug log level for the user executing the deployment.
C.Refresh the sandbox to clear any corrupted metadata.
D.Open a Salesforce support ticket immediately.
AnswerB

Increasing the log level is the most effective first step when execution data is missing. By setting the level to 'Fine' or 'Finest', the developer ensures that the platform records the full execution trace, including method calls and database operations, which is essential for diagnosing the deployment failure.

Why this answer

Effective debugging starts with ensuring the logging level is correctly configured. If logs are not capturing the flow, it is likely the log level for 'Apex Code' or 'Apex Profiling' is set to 'None' or 'Error'. Increasing the verbosity to 'Fine' or 'Finest' is the standard procedure to gain visibility into the execution path, allowing for the identification of logic errors or incorrect configuration.

Exam trap

Candidates waste time analyzing code syntax immediately instead of checking debug log levels, assuming logs capture everything by default.

45
MCQhard

A developer needs to verify that an asynchronous Apex process (Future method) executes correctly in a test environment. Which approach is best suited to ensure the test waits for the asynchronous execution to finish before asserting the results?

A.Use the Thread.sleep() method to pause the test execution until the job completes.
B.Query the AsyncApexJob table to check the status of the job before asserting.
C.Wrap the asynchronous call between Test.startTest() and Test.stopTest().
D.Use the System.enqueueJob() method within the test to monitor the job.
AnswerC

Test.stopTest() causes any asynchronous code enqueued during the Test.startTest() and Test.stopTest() block to be processed synchronously. This ensures that when the execution resumes after stopTest(), the asynchronous changes (such as database updates) are committed and available for the test class to perform its assertions correctly.

Why this answer

The Test.startTest() and Test.stopTest() methods define a block where the platform processes asynchronous operations, such as @future methods or Queueable Apex. When Test.stopTest() is called, the platform forces the completion of all asynchronous jobs within the test context, allowing the developer to assert the outcomes synchronously. This is vital for ensuring test reliability and preventing race conditions during verification.

Exam trap

Candidates often forget that asynchronous code executes outside the main test flow. They try to assert results immediately after the call, leading to race conditions where the assertion runs before the job completes.

46
MCQmedium

An enterprise development team uses Salesforce DX scratch orgs for feature development. A developer needs to ensure that unit tests execute automatically every time code is committed to the version control system. Which integration approach achieves this requirement?

A.Configure a scheduled Apex job in the scratch org to run all tests nightly and email logs to the engineering team.
B.Set up a CI/CD pipeline using GitHub Actions or Jenkins to spin up a scratch org, push metadata, and run sf apex test run.
C.Rely on developers to manually execute unit tests in their local IDE terminals before pushing commits to remote branches.
D.Configure a change set deployment validation rule that triggers whenever a pull request is opened in GitHub.
AnswerB

CI/CD tools execute headless shell scripts triggered by git push events. Running Salesforce CLI commands inside pipeline agents allows teams to create temporary scratch orgs, deploy code changes, execute tests, and enforce quality gates automatically.

Why this answer

Integrating CI/CD pipelines with version control hooks automates validation processes. Utilizing Salesforce CLI commands within CI runners guarantees that code meets quality gates and test coverage thresholds before merging into shared branches, protecting code health and reducing integration debt across large distributed development teams.

Exam trap

Candidates may mistakenly assume manual deployment scripts or unautomated sandbox validation satisfy continuous integration requirements for version control commits.

47
MCQmedium

A developer needs to deploy a complex Apex class and its corresponding test class to production. The org's unit test coverage is currently 74%. Which statement accurately describes the deployment requirements?

A.The deployment will succeed because unit tests only need to be written for the new code.
B.The deployment will fail because the aggregate code coverage must be at least 75%.
C.The developer can bypass the coverage requirement by using the 'Ignore Warnings' flag in deployment.
D.The deployment will succeed if the new Apex class itself has 75% coverage.
AnswerB

The platform requires that at least 75% of all Apex code in the org is covered by tests during production deployment. Since the current coverage is 74%, the developer must either improve existing tests or include sufficient tests for the new code to push the overall aggregate above the 75% limit.

Why this answer

Salesforce mandates a minimum of 75% code coverage for all Apex classes and triggers in an organization to deploy to production. Since the current coverage is 74%, the deployment will fail unless the new tests push the total organization coverage above the required threshold. This rule ensures that developers maintain high-quality code and provides a safety net against regressions, emphasizing the critical importance of writing effective tests during development.

Exam trap

Candidates frequently confuse the 75% requirement with a per-class requirement, mistakenly believing individual classes must hit 75% rather than the total aggregate of the entire organization.

48
MCQeasy

An integration test in a sandbox must verify that a callout to an external pricing service returns a parsed response. The test class currently attempts the real callout and fails with a 'Methods defined as TestMethod do not support Web service callouts' error. Which change should the developer make?

A.Wrap the callout in Test.startTest() and Test.stopTest() so the platform permits external requests.
B.Add the @future(callout=true) annotation to the method performing the callout.
C.Grant the running user the 'Make Callouts in Tests' permission in the test class profile.
D.Implement HttpCalloutMock and register it with Test.setMock() before the code under test invokes the callout.
AnswerD

Apex tests cannot perform real HTTP callouts, so the platform requires a mock. Implementing HttpCalloutMock and registering it with Test.setMock(HttpCalloutMock.class, mock) causes the callout to return the canned response, letting the test verify parsing and error handling deterministically without network access.

Why this answer

Apex tests are isolated from external systems, so any callout must be replaced with a mock. Implementing HttpCalloutMock and registering it via Test.setMock() lets the code under test receive a controlled response, allowing the developer to assert on parsing, status handling, and error branches without a live service.

Exam trap

The trap here is believing a governor-limit boundary or an annotation can authorize real callouts in a test, when the platform requires an injected mock instead.

49
MCQhard

Refer to the exhibit. A deployment is failing with this error. What is the most likely cause?

A.The custom field is not in the deployment package.
B.The user performing the deployment lacks field-level security.
C.The Apex class was compiled in the wrong API version.
D.The custom field needs to be marked as 'Required'.
AnswerA

This is the most direct cause. If the component, in this case, the custom field, is not included in the deployment package (or Change Set), the target org will not recognize it during compilation. The deployment fails because the Apex class references a schema item that is missing.

Why this answer

The error indicates a metadata mismatch between the source and target environments. The code references a field that hasn't been deployed or is missing from the target. A successful deployment requires all dependencies, including custom fields and objects, to be present in the target org.

Proper tracking of metadata dependencies is essential for avoiding these common deployment failures and ensuring code compatibility across different environments.

Exam trap

Test-takers often assume syntax errors are the cause of deployment failures when the actual issue is a missing metadata component.

50
MCQmedium

A developer is writing a test class for an Apex trigger that performs a callout. The developer uses a mock class implementing HttpCalloutMock. What happens if the developer fails to implement the mock interface correctly?

A.The test class will execute the real callout successfully if the endpoint is whitelisted in Remote Site Settings.
B.The trigger will process the callout using the default settings defined in Named Credentials.
C.The test will throw a CalloutException when the trigger code attempts to invoke the HTTP method.
D.The system will automatically generate a mock response based on the WSDL or OpenApi schema.
AnswerC

When an Apex unit test encounters a callout without a registered mock, it throws a CalloutException. This mechanism forces developers to define deterministic responses for their integration code, ensuring that unit tests remain fast, reliable, and independent of external service availability or network state fluctuations.

Why this answer

Apex code cannot perform real HTTP callouts during unit tests; Salesforce enforces this to prevent unpredictable external side effects. If the mock interface is not implemented or registered properly using Test.setMock, the system throws a CalloutException. Understanding this mechanism is vital for building robust integration tests, ensuring that external dependency behavior is deterministic and verifiable without hitting actual production endpoints during development cycles.

Exam trap

Candidates often mistake this for a logic error or a null pointer exception, failing to realize that the platform explicitly blocks un-mocked callouts with a specific exception type.

51
MCQhard

Refer to the exhibit. A developer attempts a deployment using Salesforce CLI. The deployment fails with the circular dependency error shown. What is the root cause of this failure?

A.The classes are missing the 'global' access modifier.
B.The deployment is using a source-format package that lacks a proper 'package.xml' file.
C.The classes share a cyclic reference, preventing the compiler from determining the initialization order.
D.The test classes for these Apex classes were not included in the deployment package.
AnswerC

Apex classes cannot have direct circular references because the compiler must resolve all dependencies before successful class compilation. When Class A calls Class B and Class B calls Class A, the system cannot verify the types and methods during the build phase, resulting in the reported deployment failure.

Why this answer

Circular dependencies occur when two Apex classes reference each other's static methods or class variables directly. During compilation, the Apex compiler cannot resolve the symbols because each class requires the other to be compiled first. This scenario highlights the importance of modular design and the use of interfaces or abstract classes to decouple interdependent logic, which allows the deployment to proceed smoothly.

Exam trap

Candidates mistakenly look for syntax errors or profile permission issues when encountering circular dependencies, missing the interlocked class references entirely.

52
MCQhard

A developer maintains a managed package and must release a new version. During packaging, the developer needs to ensure that a specific Apex class is accessible to subscriber orgs but that its implementation details remain hidden. Which packaging construct should the developer use?

A.Mark the Apex class as global and expose only global method signatures, keeping internal helper methods private.
B.Deploy the Apex class using the Metadata API with the unpackaged flag enabled to keep it outside the managed namespace.
C.Set the Apex class access to Public in the package's profile settings so subscribers can call it directly.
D.Add the Apex class to a protected custom setting so it is packaged but not exposed to subscriber code.
AnswerA

In a managed package, only global Apex members are visible and callable from outside the package namespace. Declaring the class global with a curated set of global method signatures exposes the intended API, while private and public helpers remain internal. This is the supported way to ship a public interface without revealing implementation, and it enables versioning through the package upgrade process.

Why this answer

Managed package Apex visibility is governed by the global access modifier. Declaring the class and selected methods global exposes a stable API to subscriber code across namespaces, while private helpers and internal logic stay hidden. This supports controlled upgrades because global signatures are versioned with the package.

Exam trap

The trap here is confusing profile-based Apex class access, which controls execution rights inside an org, with the global modifier that defines a managed package's cross-namespace API.

53
MCQmedium

A developer needs to write a unit test for an asynchronous future method that updates account records. How should the developer structure the test to ensure the asynchronous code executes and validates correctly?

A.Call the future method directly, then immediately query the database to verify updates without any extra context blocks.
B.Use Thread.sleep() to pause the main test thread for five seconds, giving the asynchronous queue enough time to finish processing.
C.Enclose the future method invocation between Test.startTest() and Test.stopTest() to force synchronous execution.
D.Annotate the test method with @IsTest(isAsync=true) to instruct the Apex runtime to run the test in parallel execution mode.
AnswerC

Test.startTest resets governor limits and establishes a new context where asynchronous requests are held until Test.stopTest processes them synchronously. This guarantees that all queued future jobs finish executing before subsequent assertions run in the test method.

Why this answer

Wrapping the asynchronous invocation block inside Test.startTest() and Test.stopTest() forces all asynchronous calls queued within the block to execute synchronously before Test.stopTest() completes. This pattern is fundamental in Salesforce testing because it allows developers to reliably assert database states modified by future methods, batch apex, or queueable jobs, preventing false test failures caused by execution timing races.

Exam trap

Candidates often forget that asynchronous methods execute outside the normal test transaction, leading them to assert database changes without forcing synchronous completion.

54
MCQmedium

A developer is writing a test class for a service that makes a callout to an external REST API. The test must not perform a real callout, and the developer needs to verify that the service correctly handles both a successful response and an error response. Which approach should the developer use?

A.Use HttpRequest and Http directly in the test class to simulate the external service response
B.Use Test.isRunningTest to conditionally return hardcoded responses from the service class instead of performing the callout
C.Use Test.setMock with an implementation of HttpCalloutMock that returns different responses based on the request endpoint
D.Use Test.startTest and Test.stopTest to wrap the callout and rely on the test context to intercept external requests
AnswerC

Test.setMock with HttpCalloutMock registers a mock callout handler for the test. The mock can inspect the request, including the endpoint or body, and return a success or error response accordingly. This allows the test to exercise both paths without making real callouts, and it respects the requirement that callouts in tests must be mocked.

Why this answer

HttpCalloutMock registered with Test.setMock intercepts callouts during tests and returns the response the mock defines. By inspecting the request endpoint or body, the mock can return a success payload for one path and an error status for another, letting the test validate both branches. This keeps production code free of test-specific branches and satisfies the no-real-callout rule.

Exam trap

The trap here is believing that Test.startTest or direct use of Http classes can substitute for a mock, when tests must register an HttpCalloutMock to avoid real callouts and to control responses.

55
MCQmedium

Refer to the exhibit. A developer wants to enable log filtering for a specific package. Where should this configuration be managed?

A.In the sfdx-project.json file.
B.In the Debug Logs section under Setup.
C.In the Custom Metadata Types settings.
D.In the Apex Class definition file.
AnswerB

The Debug Logs area in the Setup menu is the official location to set trace flags and debug levels. This allows developers to control log verbosity for specific users and Apex components. Managing logs here ensures that debug information is captured efficiently without impacting system performance or exceeding storage limits.

Why this answer

Log filtering and debugging levels are managed within the Salesforce Debug Logs setup. While the provided JSON snippet represents a configuration style, Apex debug settings are specifically controlled through the 'Debug Logs' section in the Setup menu, where trace flags define the granularity of logs for specific users, classes, or triggers to prevent log exhaustion.

Exam trap

Candidates often look for log settings inside the Apex class or Trigger code, not realizing that debug levels are managed globally via the Setup menu, not within the source code.

56
MCQeasy

A developer wants to ensure that their Apex code is tested against a specific set of data that is consistent across all sandbox environments. What is the best way to achieve this?

A.Hardcode the data creation in each individual @isTest method.
B.Use the @testSetup annotation to create data once per class.
C.Query for data that already exists in the environment.
D.Create a separate trigger to populate test data during deployment.
AnswerB

The @testSetup annotation provides a clean, efficient way to define common data once. When the test class runs, the setup method executes first, and its data is available for all test methods. This promotes code reuse and makes the tests more readable by separating setup from assertion logic.

Why this answer

Using @testSetup methods allows developers to create a baseline set of data that executes once for the entire test class. This ensures that every test method starts with the same data state, reducing setup redundancy and improving test reliability. This consistency is essential for debugging and ensuring that tests remain stable as the project grows and evolves over time.

Exam trap

Candidates often confuse @testSetup with traditional setup methods or assume data is created per test method, leading to redundant queries or data isolation issues.

57
Multi-Selecthard

A developer is refactoring a large legacy trigger. They want to ensure performance does not degrade while maintaining test coverage. Which TWO practices should be followed to ensure high-quality, performant testing?

Select 2 answers
A.Create a data factory class to handle object creation and common test data scenarios.
B.Insert test records within the @isTest methods to ensure data isolation for every test run.
C.Use System.runAs() to test user permissions and visibility settings for every individual record.
D.Perform bulk testing by inserting a list of 200 records to verify governor limits.
E.Use the SeeAllData=true annotation on all test classes to ensure full visibility.
AnswersA, D

Centralizing test data creation in a dedicated factory class promotes reusability and simplifies maintenance. When schema changes occur, you only need to update the factory rather than dozens of individual test classes. This pattern is a hallmark of professional Salesforce development and significantly reduces test suite fragility and technical debt.

Why this answer

Data factory classes and bulk data testing are critical for PD2-level development. Using data factories centralizes object creation, reducing maintenance overhead, while bulk testing ensures that logic performs efficiently when handling the maximum allowed batch size of 200 records. These practices prevent governor limit exceptions and ensure that the code scales effectively in a production environment with high transaction volumes.

Exam trap

Candidates frequently hardcode test data directly inside individual test methods instead of building bulkified data factories, resulting in poor scalability and duplicate code.

58
MCQeasy

A developer needs to run a single Apex test method named testBulkInsert in a class named AccountServiceTest against a sandbox org and view the results from the command line. Which Salesforce CLI command should the developer use?

A.sf apex run test --tests AccountServiceTest.testBulkInsert --target-org mySandbox --result-format human
B.sf project deploy start --test-level RunSpecifiedTests --tests AccountServiceTest.testBulkInsert
C.sf apex get test --tests AccountServiceTest.testBulkInsert --target-org mySandbox
D.sf apex run --file AccountServiceTest.cls --target-org mySandbox
AnswerA

The sf apex run test command executes Apex tests against the specified org. Using --tests with the fully qualified ClassName.methodName runs only that test method, and --result-format human prints readable results to the terminal. This is the current CLI syntax for running a targeted Apex test from the command line.

Why this answer

The sf apex run test command is the current Salesforce CLI command for executing Apex tests, and its --tests flag accepts a fully qualified ClassName.methodName to target a single method. Adding --result-format human makes the output readable in the terminal, which matches the developer's goal of running one test and viewing results from the command line.

Exam trap

The trap here is confusing sf apex run (anonymous Apex) with sf apex run test (Apex test execution), which are distinct commands.

59
MCQhard

Refer to the exhibit. A developer is deploying code using the Salesforce CLI. What is the most likely reason for this failure?

A.The deployment package contains invalid metadata syntax for the AccountTrigger component.
B.The test method failed an assertion or encountered an unhandled exception.
C.The Salesforce org has reached its storage limit, preventing new record creation in the test.
D.The CLI environment is missing the necessary permissions to execute Apex tests.
AnswerB

A test failure during deployment occurs when the test runner executes the code and the resulting state does not match the expectations set in the System.assert statements, or an unhandled exception was thrown. The deployment process requires all tests to pass to ensure the new logic is functionally sound.

Why this answer

The error indicates that the deployment failed specifically because of a unit test failure in the metadata package. Salesforce requires all tests in the deployment package to pass to ensure code quality. This process is essential for maintaining production stability, as it prevents the introduction of breaking changes, logic errors, or performance regressions that could manifest once the code is active in the production environment.

Exam trap

Candidates often assume the failure is due to deployment configuration or network issues, missing the fact that unit tests are mandatory and must pass for any metadata deployment.

Ready to test yourself?

Try a timed practice session using only Testing, Debugging, and Deployment questions.