Salesforce · Free Practice Questions · Last reviewed May 2026
30real exam-style questions organised by domain, each with the correct answer highlighted and a plain-English explanation of why it's right — and why the others are wrong.
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?
Call the future method directly, then immediately query the database to verify updates without any extra context blocks.
Use Thread.sleep() to pause the main test thread for five seconds, giving the asynchronous queue enough time to finish processing.
Enclose the future method invocation between Test.startTest() and Test.stopTest() to force synchronous execution.
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.
Annotate the test method with @IsTest(isAsync=true) to instruct the Apex runtime to run the test in parallel execution mode.
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?
Salesforce Setup Audit Trail
Salesforce Developer Console Log Inspector
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.
Salesforce Event Monitoring Analytics
Salesforce Optimizer Report
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?
Configure a scheduled Apex job in the scratch org to run all tests nightly and email logs to the engineering team.
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.
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.
Rely on developers to manually execute unit tests in their local IDE terminals before pushing commits to remote branches.
Configure a change set deployment validation rule that triggers whenever a pull request is opened in GitHub.
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?
Delete the OrderTrigger from the package manifest file, deploy the remaining components, and reinstall the trigger manually through the Salesforce UI.
Increase the Salesforce API version in the package.xml manifest to version 60.0 to bypass legacy execution blocks.
Examine the detailed deployment error logs to identify the failing test method or trigger logic, fix the root cause, and re-run validation.
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.
Run sf org logout and re-authenticate with the production environment using a different system administrator credential.
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?
Create a data factory class to handle object creation and common test data scenarios.
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.
Insert test records within the @isTest methods to ensure data isolation for every test run.
Use System.runAs() to test user permissions and visibility settings for every individual record.
Perform bulk testing by inserting a list of 200 records to verify governor limits.
Testing with a single record is insufficient because it fails to reveal potential SOQL or DML limit violations that only occur at scale. By inserting a batch of 200 records, developers ensure that their code handles Salesforce bulkification requirements correctly, preventing runtime errors in production when users perform mass operations.
Use the SeeAllData=true annotation on all test classes to ensure full visibility.
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?
The classes are missing the 'global' access modifier.
The deployment is using a source-format package that lacks a proper 'package.xml' file.
The classes share a cyclic reference, preventing the compiler from determining the initialization order.
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.
The test classes for these Apex classes were not included in the deployment package.
Want more Testing, Debugging, and Deployment practice?
Practice this domainA developer is building a complex nested Lightning Web Component structure. A deeply nested child component needs to notify an ancestor component, which is not the immediate parent, about a data change. Which configuration of the CustomEvent constructor should the developer use to ensure the event reaches the ancestor across the shadow DOM boundary?
new CustomEvent('update', { bubbles: true, composed: false });
new CustomEvent('update', { bubbles: false, composed: true });
new CustomEvent('update', { bubbles: true, composed: true });
Combining bubbles and composed properties ensures the event travels up the DOM and successfully exits the shadow DOM boundary. This is the standard approach for bubbling events to ancestors that are not direct parents, allowing the event to reach the document root or any listener registered on higher-level components.
new CustomEvent('update', { detail: { bubbles: true, composed: true } });
A developer is tasked with internationalizing a Lightning Web Component that will be deployed globally. Which TWO Salesforce features should be used to handle locale-specific formatting and translations? (Choose TWO)
@salesforce/i18n import statements
The @salesforce/i18n module provides access to locale-specific settings such as currency codes, date formats, and time zones. By importing these values, developers can use standard JavaScript Intl objects or framework utilities to format data correctly for every user, regardless of their geographical location or language settings.
Translation Workbench and Custom Labels
Custom Labels allow developers to store text strings that can be translated via the Translation Workbench. By referencing these labels in LWC via the @salesforce/label module, the framework automatically serves the version of the text that matches the user's language, facilitating easy multi-language support in the UI.
Apex Schema.DescribeFieldResult labels
Hardcoded JSON files in Static Resources
Lightning Message Service (LMS)
A developer is creating a Lightning Web Component to display a list of high-priority Opportunities. The component needs to reactively update whenever an Opportunity is updated elsewhere on the page by another component. Which approach is most efficient and requires the least amount of custom code?
Use the getRecord wire adapter to retrieve Opportunity data.
The getRecord wire adapter is built on Lightning Data Service, which maintains a client-side cache. If any other component updates the Opportunity record using LDS, the wire service automatically triggers a refresh for all components observing that record, ensuring data consistency across the UI without requiring custom refresh logic.
Implement an Apex controller with a @AuraEnabled(cacheable=true) method.
Publish a message via Lightning Message Service (LMS) after every update.
Set up a Change Data Capture (CDC) listener in the component.
A developer wants to ensure that a Lightning Web Component is only available for use on Record Pages for the Account and Contact objects in the Lightning App Builder. How should the developer configure the component's metadata file?
Define <target>lightning__RecordPage</target> and use <objects> in <targetConfig>.
This configuration correctly identifies the Record Page as a valid target for the component. By further specifying the Account and Contact objects within the targetConfig section, the developer ensures that the component only appears in the App Builder palette when those specific record types are being edited.
Use the @isTest(SeeAllData=true) annotation in the JavaScript controller.
Add the objects to the 'scoped' attribute of the component's template tag.
Set the isExposed flag to false and list the objects in a custom property.
A developer is experiencing performance issues with a Visualforce page that includes multiple complex components and a large amount of data. The page uses a standard controller with several extensions. Which technique should the developer use to reduce the view state size and improve page load time?
Mark non-essential controller variables with the 'transient' keyword.
The transient keyword prevents a variable from being included in the Visualforce view state. This is highly effective for large collections or temporary data that only needs to exist during the current request. By reducing the view state size, the developer decreases the payload sent over the network.
Replace the standard controller with a custom controller using 'without sharing'.
Wrap all input fields in an <apex:actionRegion> component.
Increase the 'apiVerson' in the Visualforce page metadata to the latest version.
Refer to the exhibit. A developer is attempting to push source code to a scratch org and encounters the error shown. The developer confirms that 'utils.js' and 'utils.js-meta.xml' exist in the 'force-app/main/default/lwc/utils/' directory. What is the most likely cause of this error?
The developer forgot to add the '@salesforce/resource' prefix to the import.
The 'utils' component is missing the 'isExposed' tag in its metadata file.
The main JavaScript file in the 'utils' folder must be named 'utils.js'.
In LWC, the main JavaScript file of a component must have the exact same name as the folder it resides in. If the folder is named 'utils', the framework expects a file named 'utils.js'. If the file is named differently, the 'c/utils' import path will fail to resolve during the compilation process.
The developer needs to run 'sfdx force:source:pull' first to sync metadata.
Want more User Interface practice?
Practice this domainA developer has a requirement to update 5,000 records in a single transaction. The operation frequently hits the 'Too many DML statements' limit. What is the most efficient way to refactor the code?
Use the Database.upsert method inside the loop.
Add the 'future' annotation to the update method.
Collect records in a list and perform one DML statement after the loop.
Performing a single DML statement on a list of records is the standard pattern for bulkifying Apex code. This approach uses only one of the 150 allowed DML statements, allowing the transaction to handle larger record volumes efficiently while significantly reducing the load on the database engine.
Increase the DML governor limit using the Apex setup menu.
A developer needs to update a field on 50,000 child records based on a change in a parent Account. What is the most performant way to handle this update?
Use a trigger to perform the update synchronously.
Implement a Batch Apex class to update in chunks.
Batch Apex processes the 50,000 records in smaller, manageable chunks, typically 200 at a time. This keeps the execution within the governor limits for each batch, allowing the entire job to complete successfully without hitting the DML limit or exhausting the CPU time allocated to a single transaction.
Use a flow with a loop and record update element.
Use the @future method in a recursive loop.
A developer is building a high-performance REST API integration. Which of the following is the most important practice for ensuring the integration handles high throughput?
Use individual REST API calls for every record update.
Utilize the Composite API to batch multiple operations.
The Composite API allows developers to combine multiple SObject operations into a single request. This drastically reduces the number of API calls needed to sync large datasets, minimizing the impact on API limits and reducing the network latency associated with multiple round-trips to the Salesforce server.
Disable all triggers during the integration process.
Increase the API timeout duration to five minutes.
Refer to the exhibit. The Apex transaction is consistently hitting the CPU limit. What is the most likely cause and the best way to optimize the code?
Replace nested loops with Map-based lookups.
Nested loops are computationally expensive, with a time complexity of O(n*m). Replacing these with a Map allows for constant time O(1) lookups, which drastically reduces the CPU cycles required for data processing. This is the most effective way to optimize logic that is causing CPU limit issues.
Reduce the batch size in the Batch Apex class.
Increase the CPU limit in the organization configuration.
Use the 'transient' keyword for all variables.
A developer is writing a query to fetch related records. Which SOQL pattern is best for avoiding unnecessary query execution and improving performance?
Perform separate queries for each record inside a loop.
Use a single relationship query to fetch parent and child records.
Relationship queries allow the retrieval of related data in one statement. This approach is highly efficient because it eliminates the need for repeated database calls, staying within governor limits and significantly reducing execution time compared to multiple individual queries performed in a loop or sequentially.
Cache all retrieved data in a static Map variable.
Use the 'FOR' loop with the 'LIMIT' keyword.
A developer needs to aggregate data from 10 million rows. Which approach is the most efficient for preventing governor limit issues?
Retrieve all records and aggregate them in an Apex loop.
Use SOQL with GROUP BY to perform aggregation in the database.
Using the GROUP BY clause allows the database engine to perform the aggregation, which is highly optimized. This approach avoids transferring large volumes of data to the Apex heap, effectively preventing memory and CPU limit errors while providing the results in a much faster, more efficient manner.
Process records in small batches using a flow.
Use a custom index on all fields involved in the query.
Want more Performance practice?
Practice this domainAn 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?
Write a @future(callout=true) method that processes the request and executes a synchronous retry loop upon catching a timeout exception.
Implement a Schedulable class that executes every minute, querying an integration staging table and performing synchronous HTTP callouts.
Create a Queueable Apex class implementing Database.AllowsCallouts, leveraging custom retry logic and job chaining when a timeout occurs.
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.
Use an InvocableMethod inside a Flow to invoke a synchronous callout immediately when the user updates the source record.
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.
Use standard Database.insert(records, true) to ensure that any single validation error rolls back the entire incoming transaction batch.
Utilize Database.insert(records, false) and iterate through the returned Database.SaveResult array to identify individual failures and construct a detailed response payload.
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.
Throw a custom CalloutException immediately upon encountering a validation error to force the Salesforce platform to rollback the REST transaction automatically.
Serialize custom error DTO objects into the HTTP response body, mapping failed record IDs to specific error messages extracted from the SaveResult errors.
Returning a structured DTO payload containing specific record IDs and corresponding error messages allows the external client to reconcile its state. This level of transparency is essential for maintaining data synchronization between distributed enterprise systems.
Rely solely on standard Apex exception logging via System.debug statements to capture transaction failures without returning response bodies.
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?
Declare instance member variables inside the batch class without implementing any special interfaces.
Implement the Database.Stateful interface on the batch class definition to preserve instance member variable states across transaction chunks.
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.
Store running totals inside static variables within the batch class, relying on the Apex transaction cache.
Write running totals to a custom metadata type record inside each execute method iteration.
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?
Execute synchronous callouts inside a scheduled Apex class running every minute to process transaction records sequentially.
Invoke the external REST service directly within a trigger handler using standard synchronous HTTP methods wrapped in a try-catch block.
Implement a Queueable Apex class with Database.AllowsCallouts, leveraging the Finalizer interface to capture failures and execute recovery logic.
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.
Configure an outbound message workflow rule that pushes XML payloads to an enterprise service bus endpoint synchronously.
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?
Global class with @RestResource(urlMapping='/api/v1/orders/*') and a static method annotated with @HttpGet returning a Blob.
Global class with @RestResource(urlMapping='/api/v1/orders/*') and a static method annotated with @HttpPost receiving parsed wrapper instances.
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.
Public webservice class with a static method annotated with @WebService returning a serialized JSON string to the calling client.
Global restful class implementing Database.Batchable with an execute method annotated with @HttpPost processing single payloads.
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?
Use an Apex trigger to perform an HTTP callout directly to the ERP system.
Configure an Outbound Message via Workflow Rule to send the data to the ERP.
Publish a Platform Event to an event bus for the ERP system to consume.
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.
Implement a scheduled batch job to query for closed opportunities and export them.
Want more Process Automation, Logic, and Integration practice?
Practice this domainWhen designing a unit test for a class that makes callouts, which pattern is the industry standard for ensuring the test does not actually send requests?
Adding the @IsTest(SeeAllData=true) annotation to the test method.
Using the System.Test.setMock() method with an implementation of HttpCalloutMock.
System.Test.setMock is the officially supported mechanism for intercepting HTTP requests during unit testing. By passing an instance of a class that implements the HttpCalloutMock interface, the developer instructs the Apex runtime to return a predefined HttpResponse object instead of initiating an actual network request to the endpoint.
Wrapping the callout code in a try-catch block to bypass execution.
Configuring a Remote Site Setting for the test domain.
A developer needs to dynamically instantiate a class at runtime based on a string value. Which feature should they use?
System.JSON.deserialize()
Type.forName()
Type.forName() accepts a string representing the fully qualified name of an Apex class and returns a Type object. This Type object can then be used to call the newInstance() method, allowing for dynamic instantiation of the class at runtime, which is essential for flexible and extensible application design.
String.valueOf()
Class.getInstance()
A developer is building a lightning component that needs to communicate with an external API. What is the recommended way to handle the secure storage of API credentials?
Storing the credentials in a custom metadata record.
Using Named Credentials with an authentication provider.
Named Credentials provide a secure, standardized way to handle external callouts. They store the endpoint URL and authentication details (like OAuth tokens or API keys) centrally. This prevents hardcoding, centralizes credential management, and ensures that the platform handles the authorization headers automatically during the request lifecycle.
Encrypting the credentials in a custom setting field.
Embedding the credentials as static constants in an Apex class.
A developer needs to execute a large number of updates to records that might trigger complex process automation. Which approach minimizes the risk of hitting governor limits?
Using the @future annotation for each record update.
Implementing the Queueable interface.
Queueable Apex is the modern standard for asynchronous work. It allows for complex logic, supports stateful variables, and enables job chaining (calling one job from another). This makes it vastly more flexible and scalable than older patterns, while also providing a higher governor limit for processing large volumes of data.
Using Database.executeBatch with a scope of 1.
Wrapping all updates in a single @ReadOnly transaction.
Refer to the exhibit. The developer observes the error above. What is the most efficient architectural change to prevent this limit from being hit?
Wrap the SOQL queries in a try-catch block to handle the exception gracefully.
Refactor the logic to collect IDs and execute a single SOQL query before the loop.
Executing a single query outside the loop allows the developer to store results in a Map. Inside the loop, the developer can then perform O(1) lookups. This pattern is the standard for bulkifying Apex code and ensures the total number of queries remains well below the limit of 100.
Increase the Apex heap size in the class definition.
Use an @future method to process each record individually.
Refer to the exhibit. The developer needs to update this code to be more robust. What is the most critical issue to address in this code snippet?
The code is not bulkified to handle a list of IDs.
The code will fail with an exception if the ID does not exist.
When an SOQL query is assigned to a single SObject variable, Salesforce expects exactly one result. If zero results are returned, a runtime exception occurs. Using a List to query the data allows the developer to check if the list is empty before attempting an update, avoiding the crash.
The code does not use 'with sharing' to enforce security.
The code uses hardcoded string values for the name.
Want more Advanced Developer Fundamentals practice?
Practice this domainThe SF-PD2 exam has 60–90 questions and must be completed in 120 minutes. The passing score is 700/1000.
Scenario-based questions covering exam objectives with detailed answer explanations.
The exam covers 5 domains: Testing, Debugging, and Deployment, User Interface, Performance, Process Automation, Logic, and Integration, Advanced Developer Fundamentals. Questions are weighted by domain — higher-weight domains appear more on your actual exam.
No. These are original exam-style practice questions written against the official Salesforce SF-PD2 exam objectives. They are not copied from the real exam. Courseiva focuses on genuine understanding, not memorisation of braindumps.
Courseiva tracks your accuracy per domain and routes you toward weak areas automatically. Free, no account required.