Courseiva

CCNA Process Automation Logic Integration Questions

33 questions · Process Automation Logic Integration topic · All types, answers revealed

1
Multi-Selecthard

A financial services organization is building a high-volume custom REST API endpoint using Apex to handle incoming transactions from an external core banking system. The integration must ensure strict data integrity, handle partial batch failures gracefully, and process up to 200 records per request. Which TWO practices must the developer implement to satisfy these requirements? Choose 2 answers.

Select 2 answers
A.Use standard Database.insert(records, true) to ensure that any single validation error rolls back the entire incoming transaction batch.
B.Utilize Database.insert(records, false) and iterate through the returned Database.SaveResult array to identify individual failures and construct a detailed response payload.
C.Throw a custom CalloutException immediately upon encountering a validation error to force the Salesforce platform to rollback the REST transaction automatically.
D.Serialize custom error DTO objects into the HTTP response body, mapping failed record IDs to specific error messages extracted from the SaveResult errors.
E.Rely solely on standard Apex exception logging via System.debug statements to capture transaction failures without returning response bodies.
AnswersB, D

Allowing partial success with Database.insert and evaluating SaveResult instances gives developers granular control over error handling. This pattern ensures valid records are persisted while exact failure reasons are captured and returned to the calling external system.

Why this answer

Using Database.insert(records, false) allows partial success processing, enabling the system to isolate failing records while committing valid ones. Returning a structured JSON response with detailed error mappings ensures the external system can reconcile transactions effectively. These patterns are vital for enterprise integration reliability and robust error handling.

Exam trap

Candidates often use standard DML statements, which cause the entire transaction to roll back on a single failure, rather than using partial DML to ensure data integrity.

2
MCQmedium

A developer is writing a test class for an Apex trigger that creates a related record when an Account is inserted. The test must verify that the related record is created and that a validation rule prevents creation when the Account's AnnualRevenue is null. What is the best practice to ensure the test covers both scenarios?

A.Use Test.startTest() and Test.stopTest() to isolate the trigger execution and then assert the results.
B.Use a single test method that inserts both a valid and an invalid Account, then asserts the results.
C.Create separate test methods for each scenario, using Test.startTest() and Test.stopTest() around the DML operation.
D.Use @isTest(SeeAllData=true) to access existing Accounts and then assert the trigger behavior.
AnswerC

Best practice is to write separate test methods for different scenarios to isolate failures and ensure comprehensive coverage. Using Test.startTest and Test.stopTest around the DML operation resets governor limits and ensures that asynchronous processes complete before assertions. This approach tests both the successful creation and the validation rule preventing creation with null AnnualRevenue.

Why this answer

The best practice is to write separate test methods for each scenario to isolate failures and ensure clarity. Wrapping the DML operations in Test.startTest and Test.stopTest resets governor limits and ensures any asynchronous processing completes. This allows the developer to assert that the related record is created for valid Accounts and that the validation rule fires for Accounts with null AnnualRevenue, achieving comprehensive test coverage.

Exam trap

The trap here is assuming that a single test method can cover multiple scenarios without interference, or that Test.startTest and Test.stopTest alone can ensure coverage.

3
Multi-Selecthard

A developer is designing a Platform Event-driven integration where an external system publishes order events and Apex subscribers update Order records. The team wants to guarantee that a transient downstream outage does not silently drop events, while also preventing duplicate order updates when the same event is redelivered. (Choose two.)

Select 2 answers
A.Increase the event delivery allocation by purchasing additional Platform Event add-on capacity so that redelivery cannot occur.
B.Make the Order update idempotent by keying on a unique event identifier stored on the Order, and skip the update if that identifier is already recorded.
C.Subscribe with a CometD client using the replayId of -1 and persist the last processed replayId, resubscribing from that stored replayId after a disconnect.
D.Configure the subscriber to use replayId -2 so that only new events are received, and rely on the external publisher to resend anything missed.
E.Use a Streaming API push topic on the Order object instead of a Platform Event so that only committed changes are streamed and duplicates are impossible.
AnswersB, C

Platform Events deliver at least once, so a redelivered event can trigger the same update twice. Recording a unique event identifier on the Order and checking it before updating makes the handler idempotent, which neutralizes duplicates regardless of how many times the event is delivered within the retention window.

Why this answer

Durability across an outage comes from persisting the last processed replayId and resubscribing from it, which replays events still inside the retention window. Because delivery is at least once, duplicate suppression must be handled in the consumer, and idempotent updates keyed on a unique event identifier accomplish that without relying on transport guarantees.

Exam trap

The trap here is believing that Platform Events deliver exactly once, so no idempotency logic is needed in the subscriber.

4
MCQmedium

A developer is writing a test class for an integration service. Which approach is required to test HTTP callouts without actually making a request to the external system?

A.Use a try-catch block to catch the callout error and bypass the mock.
B.Use Test.setMock(HttpCalloutMock.class, new MyMock());
C.Write a dummy endpoint in the external system and point the test to it.
D.Use the System.runAs() method to execute the callout as a system user.
AnswerB

Test.setMock() is the required method for registering a mock response provider. By passing the interface and an instance of the mock class, the platform will route all HTTP requests to the provided mock, enabling comprehensive testing of the integration logic without making actual outbound network requests.

Why this answer

The HttpCalloutMock interface is the standard way to simulate HTTP responses in Apex test classes. By implementing this interface and using Test.setMock(), the developer instructs the platform to intercept the callout and return a pre-defined HttpResponse object. This allows for testing various scenarios, such as successful responses and error codes, without relying on external services or network connectivity.

Exam trap

Candidates sometimes confuse callout exception handling with mocking, forgetting that Apex strictly blocks real callouts in tests unless explicitly intercepted.

5
MCQmedium

A developer is writing a test class for an Apex trigger that updates a related Contact when an Account's BillingCity changes. The trigger handler uses a SOQL query to fetch related Contacts. What is the recommended way to ensure the test class covers the trigger logic without hitting governor limits?

A.Use Test.startTest() and Test.stopTest() around the SOQL query in the trigger handler, and create test data with @TestSetup.
B.Use Test.startTest() and Test.stopTest() around the DML operation that fires the trigger, and create test data with Database.insert() without @TestSetup.
C.Use Test.startTest() and Test.stopTest() around the DML operation that fires the trigger, and create test data with @TestSetup.
D.Use Test.startTest() and Test.stopTest() around the DML operation that fires the trigger, and create test data with Test.loadData().
AnswerC

This is correct because Test.startTest() and Test.stopTest() isolate the trigger execution and reset governor limits, allowing the trigger to run within its own context. Using @TestSetup to create test data ensures that data is available for all test methods and reduces setup time. This approach helps avoid hitting governor limits by keeping the trigger logic within the test's limit boundaries.

Why this answer

The recommended approach is to use @TestSetup to create test data once for all test methods, and to wrap the DML operation that fires the trigger with Test.startTest() and Test.stopTest(). This isolates the trigger's execution and resets governor limits, ensuring the test covers the trigger logic without exceeding limits. Other options either misplace the start/stop methods or use less optimal data creation methods.

Exam trap

The trap here is assuming that Test.startTest() and Test.stopTest() should wrap the SOQL query inside the trigger, rather than the DML operation that causes the trigger to fire.

6
MCQhard

A developer must run a scheduled job that recalculates account health scores every night, but the calculation must also be triggered immediately whenever an Account record is updated during business hours. The calculation logic is already encapsulated in a Queueable class named HealthScoreQueueable. Which design meets both requirements with the least duplication and stays within platform limits?

A.Use a single Schedulable class that implements both Schedulable and Queueable interfaces, and invoke it directly from the trigger with Database.executeBatch.
B.Create a Schedulable class that enqueues HealthScoreQueueable, and from an Account trigger call System.enqueueJob with the same Queueable after checking that no matching job is already queued.
C.Implement the calculation directly inside the Account trigger using synchronous Apex, and schedule a separate Schedulable class that duplicates the same calculation logic for the nightly run.
D.Configure two separate scheduled jobs in Setup, one for nightly execution and one that runs every minute during business hours to detect Account changes and enqueue the Queueable.
AnswerB

Reusing the same Queueable from both entry points keeps the calculation logic in one place. The Schedulable wrapper satisfies the nightly schedule, while the trigger enqueues the identical class on demand; guarding with a check such as AsyncInfo or a custom flag prevents duplicate queued jobs from stacking up during rapid updates.

Why this answer

Centralizing the calculation in the existing Queueable and invoking it from both a Schedulable wrapper and the Account trigger avoids logic duplication. The duplicate-enqueue guard is essential because triggers can fire many times in one transaction, and without it the same Account could queue several identical jobs, consuming the daily asynchronous execution allowance.

Exam trap

The trap here is duplicating the calculation logic across a trigger and a scheduled class instead of reusing the single Queueable from both entry points.

7
MCQmedium

A developer needs to write an Apex test class for a service that makes a callout to an external REST API. The test must simulate different HTTP response codes, including 200, 404, and 500. Which approach should the developer use to ensure the test covers all scenarios without making actual callouts?

A.Use the @isTest(SeeAllData=true) annotation to access the external service's data directly.
B.Use a static resource to store JSON responses and parse them in the test class.
C.Use Test.setMock with a custom implementation of HttpCalloutMock that returns different responses based on the request.
D.Use Test.startTest and Test.stopTest to isolate the callout and rely on the actual external service.
AnswerC

Test.setMock allows you to specify a mock implementation for HTTP callouts. By implementing HttpCalloutMock, you can inspect the request and return a HttpResponse with the desired status code. You can create multiple mock classes or a single mock that varies responses. This is the standard way to test callouts without making real HTTP requests, ensuring tests are fast and deterministic.

Why this answer

Test.setMock with HttpCalloutMock is the correct way to simulate HTTP responses in Apex tests. It allows the developer to define custom responses for different status codes and verify that the service handles them appropriately. This approach avoids real callouts, making tests reliable and fast, and is required by Salesforce for any test that involves callouts.

Exam trap

The trap here is thinking that Test.startTest/stopTest or SeeAllData=true can handle callouts, but they do not mock HTTP requests; only Test.setMock does.

8
MCQhard

An organization wants to implement an orchestration layer that manages complex business processes spanning multiple objects and external systems. Which tool is most appropriate for managing stateful, long-running processes?

A.Apex Triggers, by updating a custom 'Status' field on the object.
B.Flow Builder using standard autolaunched flows.
C.Salesforce Orchestrator to coordinate multi-user and multi-system tasks.
D.Scheduled Apex jobs running in a nightly batch process.
AnswerC

Salesforce Orchestrator is the native solution for managing complex, stateful, and long-running business processes. It provides a visual tool to define stages and steps, allowing for the coordination of complex interactions between users and external systems that would be extremely difficult and error-prone to implement via custom Apex or basic flow.

Why this answer

Salesforce Orchestrator is designed specifically for complex, long-running business processes that involve multiple steps, users, and system interactions. Unlike basic flows or triggers, it handles state management across various stages and ensures that dependencies are met, providing a robust, visual way to monitor and coordinate complex workflows that would otherwise require significant custom development to manage state and timing.

Exam trap

Candidates often suggest standard Flows or Triggers for complex, long-running processes. They fail to realize that these tools do not natively manage the state and dependencies of multi-system, long-duration business processes.

9
MCQmedium

A developer is building a Flow that must invoke an external REST service to retrieve a customer's loyalty points. The external service requires a callout with a JSON body and returns a JSON response. The developer wants to use an External Service to simplify the integration. Which step must be completed before the Flow can use the External Service?

A.Create an Apex class that implements the HttpCalloutMock interface.
B.Configure a Remote Site Setting for the external service endpoint.
C.Register the external service using a Swagger (OpenAPI) specification.
D.Define a Connected App with OAuth settings for the external service.
AnswerC

External Services in Salesforce are created by registering an external web service using a Swagger 2.0 or OpenAPI 3.0 specification. This generates Apex classes and Flow actions that can be used declaratively. The developer must first register the service in Setup, which parses the specification and exposes the operations as invocable actions. This is the required prerequisite before referencing the service in a Flow.

Why this answer

External Services allow declarative tools like Flow to call external REST services by importing an OpenAPI (Swagger) specification. This registration step generates the necessary Apex classes and invocable actions. Without registering the service, the Flow cannot reference its operations.

The other options relate to authentication, testing, or traditional callout security, none of which are prerequisites for creating an External Service.

Exam trap

The trap here is confusing External Services with traditional Apex callouts, which require Remote Site Settings and HttpCalloutMock for testing.

10
MCQhard

A developer is building a complex asynchronous process using Queueable Apex. The process needs to make a callout to an external service, then update records based on the response. The developer implements the callout in the execute method of the Queueable class. During testing, the developer receives a 'CalloutException: Unauthorized endpoint' error. What should the developer do to resolve this?

A.Add the external service URL to the Remote Site Settings in Salesforce.
B.Move the callout to a future method instead of Queueable Apex.
C.Implement the Database.AllowsCallouts interface in the Queueable class.
D.Use a Named Credential instead of a hard-coded URL in the callout.
AnswerA

Salesforce requires that any callout to an external endpoint be authorized by adding the URL to Remote Site Settings (or using a Named Credential). The 'Unauthorized endpoint' error indicates that the endpoint is not whitelisted. Adding it to Remote Site Settings allows the callout to proceed. This is the standard solution for this error in Apex, including Queueable Apex.

Why this answer

The 'Unauthorized endpoint' error occurs when Apex attempts a callout to an endpoint not listed in Remote Site Settings or a Named Credential. The correct resolution is to add the external service URL to Remote Site Settings, which authorizes the callout. While implementing Database.AllowsCallouts is required for Queueable Apex to make callouts, it does not address endpoint authorization.

Using a Named Credential is an alternative but requires proper setup.

Exam trap

The trap here is confusing the requirement to implement Database.AllowsCallouts with the need to authorize the endpoint via Remote Site Settings or Named Credentials.

11
MCQhard

A company requires that an integration log all outbound API requests for auditing purposes, including the full request and response body. Given the potential for high volumes, which implementation is most efficient and compliant?

A.Insert a record into a custom 'Log' object synchronously within the integration class.
B.Use Platform Events to log the data asynchronously in a separate transaction.
C.Store the logs in a static variable and write to the database at the end of the day.
D.Write the logs to the Debug Log and parse them later using a log monitoring tool.
AnswerB

Platform Events allow for asynchronous, decoupled logging. The integration publishes the event and finishes the transaction immediately. A background process then handles the persistence of the log data. This ensures high performance for the main process and provides a reliable way to capture audit data without stressing governor limits.

Why this answer

Using a Platform Event to log integration data is the most efficient pattern. Because the logging happens asynchronously, it doesn't block the main business transaction. By publishing an event, a separate subscriber can handle the heavy lifting of storing the log in a custom object, ensuring the primary business operation remains performant while maintaining an audit trail for all outbound communications.

Exam trap

Candidates often suggest synchronous logging or standard DML operations within the callout transaction, which risks hitting governor limits or causing performance degradation during heavy loads.

12
MCQmedium

A developer is designing a solution where an external system must be notified in near real-time when a custom object record is created or updated. The external system exposes a REST endpoint that accepts JSON payloads. The solution must be scalable and minimize Salesforce governor limit consumption. Which approach is most appropriate?

A.Use Outbound Messages to send the record data to the external endpoint.
B.Create a trigger on the custom object that makes a synchronous callout to the external endpoint.
C.Schedule a Batch Apex job to run every 5 minutes to query updated records and call the external endpoint.
D.Use Platform Events to publish an event when the record changes, and have an external subscriber listen and call the external endpoint.
AnswerD

Platform Events provide a scalable, asynchronous messaging mechanism. When a record is created or updated, a trigger or Flow can publish a Platform Event. An external system can subscribe to the event via CometD or Pub/Sub API and then process the event, calling its own REST endpoint. This decouples Salesforce from the external system, minimizes governor limits, and supports near real-time delivery. It is the recommended pattern for this scenario.

Why this answer

Platform Events enable a scalable, asynchronous, near real-time integration pattern. Publishing an event from Salesforce and having the external system subscribe decouples the systems and avoids governor limit issues. Synchronous callouts in triggers are risky, Batch Apex is not near real-time, and Outbound Messages are SOAP-based and less flexible.

The event-driven approach is the most appropriate for this scenario.

Exam trap

The trap here is assuming that Outbound Messages or synchronous callouts are suitable for real-time REST/JSON integrations, when Platform Events offer better scalability and decoupling.

13
MCQmedium

An enterprise application requires integrating an external REST service that processes high-volume transactions asynchronously. The integration framework must handle potential connection timeouts and ensure robust error logging. Which implementation strategy meets these architectural requirements?

A.Execute synchronous callouts inside a scheduled Apex class running every minute to process transaction records sequentially.
B.Invoke the external REST service directly within a trigger handler using standard synchronous HTTP methods wrapped in a try-catch block.
C.Implement a Queueable Apex class with Database.AllowsCallouts, leveraging the Finalizer interface to capture failures and execute recovery logic.
D.Configure an outbound message workflow rule that pushes XML payloads to an enterprise service bus endpoint synchronously.
AnswerC

Queueable Apex with Database.AllowsCallouts permits asynchronous callouts, while the Finalizer interface captures unhandled failures and runs recovery logic after a timeout. This satisfies both architectural constraints: asynchronous high-volume processing and robust error logging with recovery.

Why this answer

Using Queueable Apex with the Database.AllowsCallouts interface and implementing the Finalizer interface provides a robust framework for asynchronous callouts. This combination ensures proper error handling, transaction tracking, and the ability to chain subsequent jobs if timeouts or transient connectivity issues occur in enterprise systems.

Exam trap

Candidates often choose standard @future methods, failing to realize they lack the robust error-handling, chaining, and finalizer capabilities required for complex, high-volume enterprise integration scenarios that necessitate stateful recovery logic.

14
MCQeasy

A developer is writing a test class for a service that performs a callout to an external web service. The developer needs to mock the callout response to test different scenarios without making actual HTTP requests. Which interface should the developer implement to mock the callout?

A.Database.AllowsCallouts
B.WebServiceMock
C.System.HttpMock
D.HttpCalloutMock
AnswerD

The HttpCalloutMock interface is specifically designed to mock HTTP callouts in Apex tests. By implementing this interface and its respond method, developers can return a fabricated HttpResponse without making a real callout. This allows testing of various response scenarios, including success and error cases, and is the standard approach for callout testing.

Why this answer

The HttpCalloutMock interface is the correct choice for mocking HTTP callouts in Apex tests. It allows developers to define custom responses for callouts, enabling comprehensive testing without external dependencies. WebServiceMock is for SOAP services, Database.AllowsCallouts is for enabling callouts in asynchronous Apex, and System.HttpMock is not a valid interface.

Exam trap

The trap here is confusing WebServiceMock for HTTP callout mocking, or inventing an interface like System.HttpMock, when the correct one is HttpCalloutMock.

15
MCQmedium

A developer is integrating Salesforce with an external ERP using a REST API. The ERP requires that each request include a unique correlation ID for tracing. The developer implements an Apex callout that sends the correlation ID in a custom HTTP header. During testing, the callout succeeds, but the ERP logs show that the correlation ID is missing. What is the most likely cause?

A.The header name must be prefixed with 'X-' to be recognized by the external system.
B.The custom header was added to the request after the callout was sent.
C.The HTTP request was created using a new HttpRequest() object, but the header was set on a different HttpRequest instance.
D.Salesforce automatically strips custom headers from outbound callouts for security reasons.
AnswerC

In Apex, HttpRequest objects are mutable, and headers must be set on the same instance that is passed to Http.send(). If the developer accidentally created two HttpRequest instances, setting the header on one and sending the other, the header would be absent. This is a common mistake when refactoring or copying code, and it matches the symptom of a successful callout with missing header.

Why this answer

The correct answer is that the header was set on a different HttpRequest instance than the one sent. In Apex, HttpRequest objects are not immutable; you must set headers on the same object that you pass to Http.send(). If two instances are created, the header on the unused instance is ignored, leading to the external system not receiving it.

This is a subtle but common coding error.

Exam trap

The trap here is assuming that headers can be set after the request is sent or that Salesforce strips them, rather than checking that the same HttpRequest instance is used throughout.

16
MCQhard

A developer is implementing a complex business process that requires calling an external web service, then updating multiple related records, and finally sending an email. The entire process must be atomic; if any step fails, all changes must be rolled back. Which approach should the developer use?

A.Use a Database.Savepoint and rollback in a single transaction, with the callout performed before the savepoint.
B.Perform all operations in a single Apex transaction, using a callout followed by DML and email.
C.Use a Queueable Apex job to perform the callout, then chain a second Queueable to perform DML and send email.
D.Implement a compensation mechanism: perform the callout, then DML in a separate transaction, and if DML fails, invoke a compensating callout to undo the external action.
AnswerD

Since true atomicity across external systems is impossible with Salesforce transactions, the developer must implement a compensation pattern. This involves performing the callout, then DML in a separate transaction, and if DML fails, calling the external service again to reverse the action. This achieves eventual consistency and is the standard approach for distributed transactions.

Why this answer

Atomicity across external callouts and Salesforce DML is not natively supported because callouts cannot be rolled back. The developer must use a compensation pattern: if the subsequent DML fails, a compensating callout is made to undo the external action. This ensures that the overall process either completes fully or is compensated, maintaining data integrity across systems.

Exam trap

The trap here is assuming that Salesforce transactions can provide atomicity across external callouts, or that Queueable chaining can achieve all-or-nothing behavior.

17
MCQmedium

A developer is creating a REST API endpoint in Salesforce that external systems will call to create Case records. The external system sends a JSON payload with a custom header 'X-API-Key' for authentication. The developer needs to validate this key against a custom setting before processing the request. Which Apex class should the developer use to implement this endpoint?

A.A class that implements the Queueable interface
B.A class that implements the Schedulable interface
C.A class annotated with @RestResource(urlMapping='/Cases/*')
D.A class that implements the Database.Batchable interface
AnswerC

To create a REST API endpoint in Salesforce, you define a class with the @RestResource annotation and specify a URL mapping. Inside, you define methods annotated with @HttpPost, @HttpGet, etc., to handle HTTP requests. This allows external systems to call the endpoint. The developer can then validate the 'X-API-Key' header in the method and process the request.

Why this answer

The correct approach is to use a class annotated with @RestResource and a URL mapping. This exposes the Apex class as a REST endpoint. The developer can then define a method with @HttpPost to handle incoming POST requests, validate the 'X-API-Key' header against a custom setting, and create Case records.

Other interfaces like Schedulable, Batchable, or Queueable are for asynchronous processing and do not provide REST endpoints.

Exam trap

The trap here is confusing asynchronous processing interfaces with the mechanism for exposing REST endpoints, which requires the @RestResource annotation.

18
MCQmedium

A developer is building an Apex REST service that external systems will call to create records in Salesforce. The service must enforce field-level security (FLS) and sharing rules for the running user. Which approach should the developer take to ensure these security requirements are met?

A.Use the 'without sharing' keyword and rely on the external system to send only authorized data.
B.Use the 'inherited sharing' keyword to automatically apply the sharing mode of the calling class.
C.Use the 'with sharing' keyword and assume that FLS is automatically enforced for Apex REST services.
D.Use the 'with sharing' keyword on the Apex class and manually enforce FLS using the Schema.DescribeFieldResult class.
AnswerD

Apex REST services run in system mode by default, ignoring sharing rules and FLS. To enforce sharing, the class must be declared with 'with sharing'. To enforce FLS, developers must manually check field accessibility using Schema.DescribeFieldResult and the isAccessible, isCreateable, etc., methods, or use Security.stripInaccessible. This combination ensures both sharing and FLS are respected.

Why this answer

To enforce sharing and FLS in an Apex REST service, the class must be declared 'with sharing' to respect sharing rules, and FLS must be manually enforced using Schema methods or Security.stripInaccessible. Apex runs in system mode by default, so explicit measures are required. The other options either ignore sharing, assume automatic FLS, or use an inappropriate sharing keyword.

Exam trap

The trap here is assuming that 'with sharing' alone enforces FLS, or that Apex REST services automatically enforce security, when in fact FLS must be manually enforced.

19
MCQhard

A developer is writing a test class for an Apex trigger that fires on Account insert and update. The trigger makes a callout to an external service to validate the account's billing address. The test class uses Test.setMock to mock the callout. However, when running the test, the callout is still attempted and fails with a 'Callout not allowed from test method' error. What is the most likely cause?

A.The mock class does not implement the HttpCalloutMock interface correctly, or Test.setMock was not called before the callout.
B.The trigger is performing the callout in a before insert context, which does not allow callouts.
C.The test method does not use Test.startTest() and Test.stopTest() around the callout.
D.The test class does not have the @isTest(SeeAllData=true) annotation, so it cannot access the external service.
AnswerA

The 'Callout not allowed from test method' error typically occurs when a callout is attempted without a valid mock. Even if Test.setMock is called, if the mock class does not properly implement HttpCalloutMock, or if Test.setMock is called after the callout is made, the mock will not be in effect. The mock must be set before the callout is executed. This is the most likely cause.

Why this answer

In Apex tests, callouts must be mocked using Test.setMock with a class that implements HttpCalloutMock. If the mock is not set before the callout, or if the mock class is incorrectly implemented, the test will attempt a real callout and fail with 'Callout not allowed from test method'. Ensuring the mock is properly implemented and set before the callout is the correct solution.

Exam trap

The trap here is assuming that Test.startTest() or trigger context affects callout mocking, but the real issue is the timing or correctness of the mock setup.

20
MCQhard

A developer is writing a complex asynchronous batch Apex job that processes millions of financial transaction records. The job needs to maintain running totals across batches and update a summary logging record upon completion. Which mechanism allows state to be accurately preserved across individual executeBatch transactions?

A.Declare instance member variables inside the batch class without implementing any special interfaces.
B.Implement the Database.Stateful interface on the batch class definition to preserve instance member variable states across transaction chunks.
C.Store running totals inside static variables within the batch class, relying on the Apex transaction cache.
D.Write running totals to a custom metadata type record inside each execute method iteration.
AnswerB

Database.Stateful preserves instance member variables between each executeBatch transaction, so running totals survive chunk boundaries. Without it, each batch reinitialises the class and accumulated values are lost, breaking the summary logging record update on completion.

Why this answer

Implementing the Database.Stateful interface in a Batch Apex class ensures that instance member variables retain their values across distinct transaction chunks. Without this interface, member variables reset between execute method invocations. Preserving state is essential for maintaining running totals and aggregate metrics during large-scale data processing.

Exam trap

Candidates often confuse the 'Database.Stateful' interface with the 'Database.Batchable' interface, incorrectly assuming that standard class variables automatically persist across the distinct, isolated transaction chunks of a Batch Apex job.

21
MCQmedium

Refer to the exhibit. An integration is failing when a guest user tries to access a public-facing API. What is the most likely cause, and how should it be addressed?

A.The external system needs to be whitelisted in the Remote Site Settings.
B.The Guest User profile lacks 'Read' or 'Edit' access to the requested object.
C.The API endpoint is disabled for public access in the Setup menu.
D.The integration needs to be converted to a POST request to avoid security filters.
AnswerB

The 403 error is a classic authorization error. Guest users are severely restricted by default. To fix this, you must grant the guest user profile the specific object-level and field-level permissions required for the integration. This ensures the user has access while still maintaining a secure, limited-scope configuration.

Why this answer

Guest user access is strictly controlled by the 'Guest User Access' security policy. By default, guest users have highly restricted permissions. The 403 error indicates that the Site Guest User profile lacks the necessary object or field-level permissions to read or update the data requested.

The solution is to update the profile permissions specifically, following the principle of least privilege, or use a Guest User access controller with elevated sharing access.

Exam trap

Candidates often look for complex remote site settings or missing apex classes, ignoring the fact that guest users have severely restricted default profile permissions.

22
Multi-Selecthard

A developer is implementing a Queueable Apex job that makes a callout to an external REST service and then updates records in Salesforce. The job must handle failures gracefully and allow chaining to a second job if needed. Which two practices should the developer follow? (Choose two.)

Select 2 answers
A.Implement the Database.AllowsCallouts interface in the Queueable class.
B.Use the @future annotation with (callout=true) to make the callout, and chain a new future method for subsequent processing.
C.Use the System.schedule method to schedule the job to run at a later time, and handle errors with a try-catch block.
D.Use the System.enqueueJob method to chain a new job from within the execute method, and implement the Finalizer interface to handle errors.
E.Implement the Database.Stateful interface to maintain state across chained jobs.
AnswersA, D

This is correct because Queueable Apex jobs that perform callouts must implement Database.AllowsCallouts. Without this interface, the job cannot make HTTP callouts to external services. The interface grants the job permission to make callouts, which are otherwise restricted in asynchronous Apex. This is a mandatory requirement for any Queueable job that includes callout logic.

Why this answer

To make callouts from a Queueable job, the class must implement Database.AllowsCallouts. To chain a second job and handle errors gracefully, the developer should use System.enqueueJob within the execute method and implement the Finalizer interface. These two practices ensure the job can perform callouts and manage chaining and error handling as required.

Exam trap

The trap here is confusing Queueable chaining with Batch Apex state or @future methods, which do not support chaining or callouts in the same way.

23
MCQeasy

A developer needs to write an Apex test class for a service that makes a callout to an external REST API. The test method must simulate the callout response without making an actual HTTP request. Which approach should the developer use?

A.Annotate the test method with `@isTest(SeeAllData=true)` to allow the callout to access external data.
B.Replace the callout with a `@future` method and test the future method using `Test.stopTest` to force execution.
C.Implement the `HttpCalloutMock` interface and use `Test.setMock` to register the mock before calling the service method.
D.Use `Test.startTest` and `Test.stopTest` to isolate the callout and prevent it from executing during the test.
AnswerC

This option is correct because `HttpCalloutMock` is the standard interface for mocking HTTP callouts in Apex tests. By implementing the `respond` method and registering the mock with `Test.setMock(HttpCalloutMock.class, mockInstance)`, the test can simulate the external response without making a real callout. This is the required approach for testing callouts in Apex.

Why this answer

The correct approach is to implement the `HttpCalloutMock` interface and register it with `Test.setMock`. This allows the test to simulate the external API response without making a real HTTP request. Other options do not provide a way to mock callouts; they either do not prevent the callout or are unrelated to mocking.

Exam trap

The trap here is thinking that `Test.startTest` or `@isTest(SeeAllData=true)` can handle callouts, when only `HttpCalloutMock` can simulate them.

24
MCQmedium

A developer is building a Lightning web component that needs to retrieve a large dataset from a custom object and display it in a paginated table. The component must minimize the number of server round-trips and adhere to Salesforce governor limits. Which approach should the developer use?

A.Use a `@wire` adapter with `getRecord` to fetch all records at once and implement client-side pagination.
B.Use the `lightning-datatable` component with the `getRecords` wire adapter to fetch data in chunks.
C.Use an Apex controller with `@AuraEnabled(cacheable=true)` and implement keyset pagination using `WHERE` clauses on an indexed field.
D.Use an Apex controller with `@AuraEnabled(cacheable=true)` and implement pagination using `OFFSET` in SOQL queries.
AnswerC

This option is correct because keyset pagination uses `WHERE` clauses on indexed fields to fetch the next set of records, avoiding the performance overhead of `OFFSET`. It minimizes server round-trips by fetching only the required records. The `cacheable=true` annotation allows client-side caching, improving performance. This approach adheres to governor limits and scales well for large datasets.

Why this answer

Keyset pagination using `WHERE` clauses on indexed fields is the recommended approach for large datasets. It avoids the performance degradation of `OFFSET` and minimizes server round-trips by fetching only the needed records. Using `@AuraEnabled(cacheable=true)` allows caching, further reducing server calls.

This method adheres to governor limits and provides efficient pagination.

Exam trap

The trap here is assuming that `OFFSET` is suitable for pagination, when it becomes inefficient for large datasets due to full table scans.

25
MCQeasy

A developer needs to write a SOQL query that retrieves all Account records with their related Opportunities, but only Opportunities that are in the 'Closed Won' stage. Which SOQL query correctly achieves this?

A.SELECT Id, Name, (SELECT Id, Name FROM Opportunities WHERE StageName = 'Closed Won') FROM Account WHERE StageName = 'Closed Won'
B.SELECT Id, Name, (SELECT Id, Name FROM Opportunities WHERE StageName = 'Closed Won') FROM Account
C.SELECT Id, Name, (SELECT Id, Name FROM Opportunities WHERE StageName = 'Closed Won') FROM Account WHERE Id IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Closed Won')
D.SELECT Id, Name, (SELECT Id, Name FROM Opportunities) FROM Account WHERE Opportunities.StageName = 'Closed Won'
AnswerB

This query uses a subquery to retrieve related Opportunities filtered by StageName. The subquery is enclosed in parentheses and placed in the SELECT clause. It correctly returns all Accounts, and for each Account, only the Opportunities that are Closed Won. This is the standard way to query parent-child relationships with filters on the child records.

Why this answer

The correct query uses a subquery in the SELECT clause to retrieve related Opportunities with a filter on StageName. This returns all Accounts and includes only Closed Won Opportunities for each. Filtering child records must be done within the subquery.

The other options either incorrectly filter in the outer query, fail to filter the child records, or reference a non-existent field on Account.

Exam trap

The trap here is trying to filter child records in the outer WHERE clause or assuming that a subquery in the WHERE clause filters the child records in the result.

26
MCQmedium

An architect needs to expose custom Apex business logic as a RESTful web service that accepts complex JSON payloads containing polymorphic relationships. Which annotation and method signature combination should a developer use to implement this endpoint?

A.Global class with @RestResource(urlMapping='/api/v1/orders/*') and a static method annotated with @HttpGet returning a Blob.
B.Global class with @RestResource(urlMapping='/api/v1/orders/*') and a static method annotated with @HttpPost receiving parsed wrapper instances.
C.Public webservice class with a static method annotated with @WebService returning a serialized JSON string to the calling client.
D.Global restful class implementing Database.Batchable with an execute method annotated with @HttpPost processing single payloads.
AnswerB

A global class exposing @RestResource with a URL mapping, plus a static @HttpPost method accepting deserialised wrapper instances, lets Apex parse complex JSON including polymorphic types. Wrappers give explicit typed fields, which Apex requires because it cannot natively bind polymorphic JSON to a single concrete type.

Why this answer

Apex REST services are exposed using the @RestResource annotation on a global class. The inbound HTTP POST method must be annotated with @HttpPost and accept parameters that map directly to the incoming JSON structure using Apex deserialization or wrapper classes.

Exam trap

Candidates often forget the required global access modifier on the class or select incorrect annotations for HTTP methods, causing the endpoint to fail registration or execution.

27
MCQhard

A developer is designing a solution to process large volumes of incoming JSON data from an external system. The data must be transformed and loaded into multiple related custom objects. The processing must handle up to 1 million records per day and be resilient to failures. Which combination of features should the developer use to meet these requirements?

A.Use a Scheduled Apex job that invokes a Batch Apex class to process the data, with Database.Stateful to maintain state across batches.
B.Use Platform Events to publish each record and an Apex trigger to process them asynchronously.
C.Use a Flow with a Loop element to process each record and an Apex Action to perform DML operations.
D.Use a Queueable Apex job that chains itself to process records in chunks, with a final job to update related objects.
AnswerA

Batch Apex is designed for processing large data volumes. By implementing Database.Stateful, the class can maintain state across batch executions, which is useful for tracking progress or accumulating results. Scheduling the batch allows daily processing. This approach is scalable, handles governor limits by chunking, and provides resilience through batch retries if configured.

Why this answer

Batch Apex is the optimal solution for processing large data volumes. It breaks the data into chunks, respects governor limits, and can maintain state with Database.Stateful. Scheduling the batch ensures daily processing.

Other options either have scalability limits (Queueable, Flow) or are not designed for bulk data (Platform Events). The developer should also consider using Database.AllowsCallouts if needed.

Exam trap

The trap here is underestimating the scalability of Queueable Apex or overestimating Flow limits, leading to a solution that fails at high volumes.

28
MCQmedium

Refer to the exhibit. The service is failing because the external system requires a specific 'Content-Type' header that is missing. Which addition to the code will correctly resolve this issue?

A.req.setHeader('Content-Type', 'application/json');
B.req.setBody('Content-Type: application/json');
C.req.setMethod('Content-Type: application/json');
D.h.setHeader('Content-Type', 'application/json');
AnswerA

Setting the 'Content-Type' header explicitly informs the external server about the format of the data being sent. This is a standard requirement for RESTful APIs and ensures the server correctly parses the request body, preventing 415 Unsupported Media Type or similar errors in the integration handshake.

Why this answer

To successfully communicate with an external API that expects specific metadata, the HTTP request must be configured with the necessary headers before the request is sent. The HttpRequest class provides the setHeader() method, which is the standard way to define metadata such as 'Content-Type' or 'Authorization'. Adding this line ensures the request is formatted correctly for the external system's expectations.

Exam trap

Candidates often assume the HttpRequest object is automatically configured for JSON. They forget that external systems strictly validate headers, leading to failures if the Content-Type is missing or incorrectly set.

29
MCQhard

A developer is building a Lightning web component that needs to display a list of accounts with their related contacts. The component uses a wire adapter to call an Apex method that returns a list of Account objects with a nested list of Contacts. The developer notices that the contacts are not displayed, and the Apex method returns the accounts correctly. What is the most likely cause?

A.The Apex method does not query the related contacts using a subquery or separate query, so the contact data is not included in the result.
B.The Apex method returns a list of Account objects, but Lightning web components cannot handle nested objects in wire adapters.
C.The Lightning web component does not use the @wire decorator correctly, so the data is not reactive.
D.The Apex method does not use the @AuraEnabled(cacheable=true) annotation, so the wire adapter cannot cache the data.
AnswerA

To include related records in an Apex method result, the SOQL query must explicitly retrieve them, typically using a subquery like SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account. If the developer only queries accounts, the contacts list will be empty. This is the most common oversight when returning parent-child data to Lightning web components.

Why this answer

The most likely cause is that the Apex method's SOQL query does not include the related contacts. To return parent-child data, the query must use a subquery or a separate query to fetch contacts. Without that, the contacts list will be empty.

The wire adapter and component can handle nested data, but the data must be present in the Apex result. Ensuring the query includes the child records resolves the issue.

Exam trap

The trap here is assuming that the wire adapter or component cannot handle nested data, when the real issue is the Apex query not retrieving child records.

30
MCQeasy

A developer must write a test method for an Apex service that performs an HTTP callout to a shipping-rate API. The test must not reach the external service and must assert that the service handles a successful response. Which approach is required?

A.Set the endpoint URL to a static resource path in the test and rely on the platform to serve the canned response from that resource.
B.Annotate the test method with @isTest(SeeAllData=true) so the test can reach the external service and receive real shipping rates, then assert on the returned values.
C.Implement the HttpCalloutMock interface, register it with Test.setMock, and inside the mock's respond method return an HttpResponse constructed with the desired status code and body.
D.Wrap the callout in Test.startTest and Test.stopTest; the framework automatically blocks outbound callouts during tests and returns a default 200 response.
AnswerC

Test.setMock with an HttpCalloutMock implementation intercepts callouts made during the test, so no external request leaves the platform. The mock's respond method supplies a synthetic HttpResponse, letting the test assert the service's parsing and success-path behavior deterministically without depending on the live shipping API.

Why this answer

Apex tests cannot perform real callouts, so the only way to exercise callout code is to register a mock through Test.setMock. The HttpCalloutMock implementation returns a fabricated HttpResponse, which makes the success path testable and repeatable while guaranteeing that no traffic reaches the shipping-rate API.

Exam trap

The trap here is assuming that wrapping callout code in Test.startTest and Test.stopTest makes the platform return a default successful response.

31
MCQmedium

An enterprise application requires integrating an external REST API that frequently times out. A developer needs to implement a robust outbound callout mechanism in Apex that handles asynchronous execution while supporting complex retry policies and transactional state management. Which architectural approach best meets these requirements?

A.Write a @future(callout=true) method that processes the request and executes a synchronous retry loop upon catching a timeout exception.
B.Implement a Schedulable class that executes every minute, querying an integration staging table and performing synchronous HTTP callouts.
C.Create a Queueable Apex class implementing Database.AllowsCallouts, leveraging custom retry logic and job chaining when a timeout occurs.
D.Use an InvocableMethod inside a Flow to invoke a synchronous callout immediately when the user updates the source record.
AnswerC

Queueable Apex supports complex object serialization, making it ideal for passing large payloads to external services. Implementing the Database.AllowsCallouts interface permits HTTP requests, and job chaining allows developers to implement sophisticated back-off and retry mechanisms safely.

Why this answer

Queueable Apex implementing Database.AllowsCallouts is the optimal choice for asynchronous HTTP callouts in Salesforce. It supports chaining jobs, passing complex data types as member variables, and provides robust error handling compared to future methods. Mastering asynchronous processing patterns ensures application resilience and prevents governor limit violations during high-volume enterprise integrations.

Exam trap

Candidates often default to future methods, which lack the ability to chain jobs or handle complex object states, making them insufficient for robust enterprise-grade retry logic.

32
MCQmedium

A business process requires that when a high-value Opportunity is closed, an external ERP system is notified via an event-driven architecture. Which solution provides the most decoupled and scalable integration pattern?

A.Use an Apex trigger to perform an HTTP callout directly to the ERP system.
B.Configure an Outbound Message via Workflow Rule to send the data to the ERP.
C.Publish a Platform Event to an event bus for the ERP system to consume.
D.Implement a scheduled batch job to query for closed opportunities and export them.
AnswerC

Platform Events facilitate an asynchronous, decoupled architecture where Salesforce publishes changes to the event bus. This approach ensures that the primary transaction completes quickly while the ERP system consumes events independently. This pattern is highly scalable and fault-tolerant, perfectly aligning with modern enterprise integration requirements for reliable system communication.

Why this answer

Platform Events are the ideal choice for this architecture. They allow the Salesforce environment to publish an event message that is completely decoupled from the subscriber. This provides high scalability, as the ERP system can subscribe to the events at its own pace without impacting the transaction performance of the originating Salesforce process, ensuring that the business requirements are met with maximum system resilience.

Exam trap

Candidates often suggest synchronous Apex or triggers for external integration, failing to recognize that these tightly couple the systems and can cause performance issues if the external system is slow.

33
MCQhard

Refer to the exhibit. An Apex trigger is failing during a mass update of records. The developer identifies that the SOQL query is inside a loop. Which pattern must be applied to fix this error while maintaining the required functionality?

A.Increase the SOQL query limit by using a @future method to perform the query.
B.Collect all IDs in a Set and execute a single SOQL query outside the loop.
C.Use the Database.queryAll() method to bypass standard governor limits.
D.Wrap the loop in a try-catch block to ignore the error and proceed with the remaining records.
AnswerB

Bulkifying the SOQL query by using a Set to gather IDs and executing the query once outside the loop ensures the code remains well within the 100-query governor limit. This approach is highly performant and the industry-standard way to write scalable Apex triggers that handle bulk data operations.

Why this answer

The 'Too many SOQL queries: 101' error is the most common indicator of a 'SOQL query in a loop' anti-pattern. To fix this, the developer must move the query outside the loop by collecting the necessary IDs into a Set or List first. Then, perform a single SOQL query that fetches all required records at once, storing them in a Map for efficient, constant-time retrieval during the trigger execution.

Exam trap

Candidates often try to solve the loop query problem by simply moving the query, but they fail to use a Map to retrieve the data efficiently, resulting in poor performance.

Ready to test yourself?

Try a timed practice session using only Process Automation Logic Integration questions.