Test Class
Contains methods related to Apex tests.
The following are methods for Test. All methods are static.
-
calculatePermissionSetGroup(psgIds)
Calculates aggregate permissions in specified permission set groups for testing.
-
calculatePermissionSetGroup(psgId)
Calculates aggregate permissions in a specified permission set group for testing.
-
Clear the messages on a Visualforce page while executing Apex test methods.
-
createSoqlStub(targetType, soqlStub)
Creates a stub that will respond to SOQL queries against the specified SObject type you can use during testing.
-
createStub(parentType, stubProvider)
Creates a stubbed version of an Apex class that you can use for testing. This method is part of the Apex stub API. You can use it with the
System.StubProviderinterface to create a mocking framework. -
createStubQueryRow(targetType, fieldMapWithRelationshipKeys)
Creates an instance of a stubbed SObject type that you can use to provide testing results in the extended
System.SoqlStubProviderclass. -
createStubQueryRows(targetType, fieldMapWithRelationshipKeysForMultipleRows)
Creates instances of stubbed SObject types that you can use to provide testing results in the extended
System.SoqlStubProviderclass. -
Use this method in an Apex test so that change event notifications are generated for all supported Change Data Capture entities. Call this method at the beginning of your test before performing DML operations and calling
Test.getEventBus().deliver();. -
enqueueBatchJobs(numberOfJobs)
Adds the specified number of jobs with no-operation contents to the test-context queue. It first fills the test batch queue, up to the maximum 5 jobs, and then places jobs in the test flex queue. It throws a limit exception when the number of jobs in the test flex queue exceeds the allowed limit of 100 jobs.
-
Returns an instance of the test event bus broker, which lets you operate on platform event or change event messages in an Apex test. For example, you can call
Test.getEventBus().deliver()to deliver event messages. -
Returns an ordered list of job IDs for jobs in the test-context flex queue. The job at index
0is the next job slated to run. This method returns only test-context results, even if it’s annotated with@IsTest(SeeAllData=true). -
Returns the ID of the standard price book in the organization.
-
invokeContinuationMethod(controller, request)
Invokes the callback method for the specified controller and continuation in a test method.
-
Returns
trueif the currently executing code was called by code contained in a test method,falseotherwise. Use this method if you need to run different code depending on whether it was being called from a test. -
Returns
trueif a SOQL stub is defined for an SObject type; otherwise returnsfalse. -
loadData(sObjectToken, resourceName)
Inserts test records from the specified static resource .csv file and for the specified sObject type, and returns a list of the inserted sObjects.
-
testNotificationActionHandler (handler, actionableNotification)
Tests a notification action handler implementation by simulating the execution of an action for a specific notification.
-
newSendEmailQuickActionDefaults(contextId, replyToId)
Creates a new QuickAction.SendEmailQuickActionDefaults instance for testing a class implementing the QuickAction.QuickActionDefaultsHandler interface.
-
setContinuationResponse(requestLabel, mockResponse)
Sets a mock response for a continuation HTTP request in a test method.
-
setCreatedDate(recordId, createdDatetime)
Sets
CreatedDatefor a test-context sObject. -
A Visualforce test method that sets the current PageReference for the controller.
-
A Visualforce test method that sets the current PageReference for the controller.
-
setFixedSearchResults(fixedSearchResults)
Defines a list of fixed search results to be returned by all subsequent SOSL statements in a test method.
-
setMock(interfaceType, instance)
Sets the response mock mode and instructs the Apex runtime to send a mock response whenever a callout is made through the HTTP classes or the auto-generated code from WSDLs.
-
setReadOnlyApplicationMode(applicationMode)
Sets the application mode for an organization to read-only in an Apex test to simulate read-only mode during Salesforce upgrades and downtimes. The application mode is reset to the default mode at the end of each Apex test run.
-
Marks the point in your test code when your test actually begins. Use this method when you are testing governor limits.
-
Marks the point in your test code when your test ends. Use this method in conjunction with the
startTestmethod. -
testInstall(installImplementation, version, isPush)
Tests the implementation of the InstallHandler interface, which is used for specifying a post install script in packages. Tests run as the test initiator in the development environment.
-
testSandboxPostCopyScript(script, organizationId, sandboxId, sandboxName)
Tests the implementation of the SandboxPostCopy Interface, which is used for specifying a script to run at the completion of a Sandbox copy. Tests run as the test initiator in the development environment.
-
testSandboxPostCopyScript(script, organizationId, sandboxId, sandboxName, RunAsAutoProcUser)
Tests the implementation of the SandboxPostCopy Interface, which is used for specifying a script to run at the completion of a Sandbox copy. When
RunAsAutoProcUseristrue, tests run as Automated Process user in the development environment. -
testUninstall(uninstallImplementation)
Tests the implementation of the UninstallHandler interface, which is used for specifying an uninstall script in packages. Tests run as the test initiator in the development environment.
Calculates aggregate permissions in specified permission set groups for testing.
public static void calculatePermissionSetGroup(List<String> psgIds)
Type: void
Calculates aggregate permissions in a specified permission set group for testing.
public static void calculatePermissionSetGroup(String psgId)
- psgId: Type: String A single ID for a specified permission set group.
Type: void
Clear the messages on a Visualforce page while executing Apex test methods.
public static void clearApexPageMessages()
Type: void
This method may only be used in tests.
Creates a stub that will respond to SOQL queries against the specified SObject type you can use during testing.
public static void createSoqlStub(Schema.SObjectType targetType, System.SoqlStubProvider soqlStub)
- targetType: Type: Schema.SObjectType The SObject type to be stubbed. This parameter can’t be null.
- soqlStub: Type: System.SoqlStubProvider An implementation of the
SoqlStubProviderabstract class.
Type: void
See Also
Creates a stubbed version of an Apex class that you can use for testing. This method is part of the Apex stub API. You can use it with the System.StubProvider interface to create a mocking framework.
public static Object createStub(System.Type parentType, System.StubProvider stubProvider)
- parentType: Type: System.Type The type of the Apex class to be stubbed.
- stubProvider: System.StubProvider An implementation of the
StubProviderinterface.
Type: Object
Returns the stubbed object to use in testing.
The createStub() method works together with the System.StubProvider interface. You define the behavior of the stubbed object by implementing the StubProvider interface. Then you create a stubbed object using the createStub() method. When you invoke methods on the stubbed object, the handleMethodCall() method of the StubProvider interface is called to perform the behavior of the stubbed method.
See Also
Creates an instance of a stubbed SObject type that you can use to provide testing results in the extended System.SoqlStubProvider class.
public static SObject createStubQueryRow(Schema.SObjectType targetType, Map<String,Object> fieldMapWithRelationshipKeys)
- targetType: Type: Schema.SObjectType The SObject type to be stubbed. This parameter can’t be null.
- fieldMapWithRelationshipKeys: Type: Map<String,Object> The map contains the fields for a parent entity, keyed by the field name with a value for each field. Key and value pairs can also be used for an aggregate relationship. The key holds the name of the aggregate relationship and the value is a list of SObjects.
Type: SObject
Returns the stubbed SObject to use in testing.
See Also
Creates instances of stubbed SObject types that you can use to provide testing results in the extended System.SoqlStubProvider class.
public static List<SObject> createStubQueryRows(Schema.SObjectType targetType, List<Map<String,Object>> fieldMapWithRelationshipKeysForMultipleRows)
- targetType: Type: Schema.SObjectType The SObject type to be stubbed. This parameter can’t be null.
- fieldMapWithRelationshipKeysForMultipleRows: Type: List<Map<String,Object>> The list of maps containing the fields for a parent entity, keyed by the field name with a value for each field. Key and value pairs can also be used for an aggregate relationship used in the query. The key holds the name of the aggregate relationship and the value is a list of SObjects.
Type: List<SObject>
Returns a list of stubbed SObject types to use in testing.
See Also
Use this method in an Apex test so that change event notifications are generated for all supported Change Data Capture entities. Call this method at the beginning of your test before performing DML operations and calling Test.getEventBus().deliver();.
public static void enableChangeDataCapture()
Type: void
The enableChangeDataCapture() method ensures that Apex tests can fire change event triggers regardless of the entities selected in Setup in the Change Data Capture page. The enableChangeDataCapture() method doesn’t affect the entities selected in Setup.
See Also
Adds the specified number of jobs with no-operation contents to the test-context queue. It first fills the test batch queue, up to the maximum 5 jobs, and then places jobs in the test flex queue. It throws a limit exception when the number of jobs in the test flex queue exceeds the allowed limit of 100 jobs.
public static List<Id> enqueueBatchJobs(Integer numberOfJobs)
- numberOfJobs: Type: Integer Number of test jobs to enqueue.
A list of IDs of enqueued test jobs.
Use this method to reduce testing time. Instead of using your org’s real batch jobs for testing, you can use this method to simulate batch-job enqueueing. Using enqueueBatchJobs(numberOfJobs) is faster than enqueuing real batch jobs.
Returns an instance of the test event bus broker, which lets you operate on platform event or change event messages in an Apex test. For example, you can call Test.getEventBus().deliver() to deliver event messages.
public static EventBus.TestBroker getEventBus()
Type: EventBus.TestBroker
A broker for the test event bus.
Enclose Test.getEventBus().deliver() within the Test.startTest() and Test.stopTest() statement block.
See Also
Returns an ordered list of job IDs for jobs in the test-context flex queue. The job at index 0 is the next job slated to run. This method returns only test-context results, even if it’s annotated with @IsTest(SeeAllData=true).
public static List<Id> getFlexQueueOrder()
An ordered list of IDs of the jobs in the test’s flex queue.
Returns the ID of the standard price book in the organization.
public static Id getStandardPricebookId()
Type: Id
The ID of the standard price book.
This method returns the ID of the standard price book in your organization regardless of whether the test can query organization data. By default, tests can’t query organization data unless they’re annotated with @isTest(SeeAllData=true).
Creating price book entries with a standard price requires the ID of the standard price book. Use this method to get the standard price book ID so that you can create price book entries in your tests.
This example creates some test data for price book entries. The test method in this example gets the standard price book ID and uses this ID to create a price book entry for a product with a standard price. Next, the test creates a custom price book and uses the ID of this custom price book to add a price book entry with a custom price.
Invokes the callback method for the specified controller and continuation in a test method.
public static Object invokeContinuationMethod(Object controller, Continuation request)
- controller: Type: Object An instance of the controller class that invokes the continuation request.
- request: Type: Continuation The continuation that is returned by an action method in the controller class.
Type: Object
The response of the continuation callback method.
Use the Test.setContinuationResponse and Test.invokeContinuationMethod methods to test continuations. In test context, callouts of continuations aren’t sent to the external service. By using these methods, you can set a mock response and cause the runtime to call the continuation callback method to process the mock response.
Call Test.setContinuationResponse before you call Test.invokeContinuationMethod. When you call Test.invokeContinuationMethod, the runtime executes the callback method that is associated with the continuation. The callback method processes the mock response that is set by Test.setContinuationResponse.
Returns true if the currently executing code was called by code contained in a test method, false otherwise. Use this method if you need to run different code depending on whether it was being called from a test.
public static Boolean isRunningTest()
Type: Boolean
Returns true if a SOQL stub is defined for an SObject type; otherwise returns false.
public static Boolean isSoqlStubDefined(Schema.SObjectType targetType)
- targetType: Type: Schema.SObjectType The SObject type to check. This parameter can’t be null.
Type: Boolean
Inserts test records from the specified static resource .csv file and for the specified sObject type, and returns a list of the inserted sObjects.
public static List<sObject> loadData(Schema.SObjectType sObjectToken, String resourceName)
- sObjectToken: Type: Schema.SObjectType The sObject type for which to insert test records.
- resourceName: Type: String The static resource that corresponds to the .csv file containing the test records to load. The name is case insensitive.
You must create the static resource prior to calling this method. The static resource is a comma-delimited file ending with a .csv extension. The file contains field names and values for the test records. The first line of the file must contain the field names and subsequent lines are the field values. To learn more about static resources, see “Defining Static Resources” in the Salesforce online help.
Once you create a static resource for your .csv file, the static resource will be assigned a MIME type. Supported MIME types are:
- text/csv
- application/vnd.ms-excel
- application/octet-stream
- text/plain
Tests a notification action handler implementation by simulating the execution of an action for a specific notification.
Type: Messaging.ActionResult
The result object generated by the handler, typically containing success status and any relevant error messages or return data.
This method allows you to perform unit tests on custom notification logic without needing to trigger an actual push notification through the platform. Use this in conjunction with Assert methods to verify that your handler processes inputs correctly and returns the expected ActionResult.
The following example demonstrates how to use testNotificationActionHandler to verify a custom handler named LeadAssignmentHandler.
Creates a new QuickAction.SendEmailQuickActionDefaults instance for testing a class implementing the QuickAction.QuickActionDefaultsHandler interface.
public static QuickAction.SendEmailQuickActionDefaults newSendEmailQuickActionDefaults(ID contextId, ID replyToId)
- contextId: Type: Id Parent record of the email message.
- replyToId: Type: Id Previous email message ID if this email message is a reply.
Type: SendEmailQuickActionDefaults Class
The default values used for an email message quick action.
Sets a mock response for a continuation HTTP request in a test method.
public static void setContinuationResponse(String requestLabel, System.HttpResponse mockResponse)
- requestLabel: Type: String The unique label that corresponds to the continuation HTTP request. This label is returned by
Continuation.addHttpRequest. - mockResponse: Type: HttpResponse The fake response to be returned by
Test.invokeContinuationMethod.
Type: void
Use the Test.setContinuationResponse and Test.invokeContinuationMethod methods to test continuations. In test context, callouts of continuations aren’t sent to the external service. By using these methods, you can set a mock response and cause the runtime to call the continuation callback method to process the mock response.
Call Test.setContinuationResponse before you call Test.invokeContinuationMethod. When you call Test.invokeContinuationMethod, the runtime executes the callback method that is associated with the continuation. The callback method processes the mock response that is set by Test.setContinuationResponse.
Sets CreatedDate for a test-context sObject.
public static void setCreatedDate(Id recordId, Datetime createdDatetime)
- recordId: Type: Id The ID of an sObject.
- createdDatetime: Type: Datetime The value to assign to the sObject’s
CreatedDatefield.
Type: void
All database changes are rolled back at the end of a test. You can’t use this method on records that existed before your test executed. You also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in your org. If you set CreatedDate to a future value, it can cause unexpected results. This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.
Insert your test record before you set its CreatedDate, as shown in this example.
A Visualforce test method that sets the current PageReference for the controller.
public static Void setCurrentPage(PageReference page)
- page: Type: System.PageReference
Type: Void
A Visualforce test method that sets the current PageReference for the controller.
public static Void setCurrentPageReference(PageReference page)
- page: Type: System.PageReference
Type: Void
Defines a list of fixed search results to be returned by all subsequent SOSL statements in a test method.
public static Void setFixedSearchResults(ID[] fixedSearchResults)
- fixedSearchResults: Type: ID[] The list of record IDs specified by opt_set_search_results replaces the results that would normally be returned by the SOSL queries if they were not subject to any
WHEREorLIMITclauses. If these clauses exist in the SOSL queries, they are applied to the list of fixed search results.
Type: Void
If opt_set_search_results is not specified, all subsequent SOSL queries return no results.
For more information, see Dynamic SOSL.
Sets the response mock mode and instructs the Apex runtime to send a mock response whenever a callout is made through the HTTP classes or the auto-generated code from WSDLs.
public static Void setMock(Type interfaceType, Object instance)
- interfaceType: Type: System.Type
- instance: Type: Object
Type: Void
To mock a callout if the code that performs the callout is in a managed package, call Test.setMock from a test method in the same package with the same namespace.
Sets the application mode for an organization to read-only in an Apex test to simulate read-only mode during Salesforce upgrades and downtimes. The application mode is reset to the default mode at the end of each Apex test run.
public static Void setReadOnlyApplicationMode(Boolean applicationMode)
- applicationMode: Type: Boolean
Type: Void
Also see the getApplicationReadWriteMode() System method.
Do not use setReadOnlyApplicationMode for purposes unrelated to Read-Only Mode testing, such as simulating DML exceptions.
The following example sets the application mode to read-only and attempts to insert a new account record, which results in the exception. It then resets the application mode and performs a successful insert.
Marks the point in your test code when your test actually begins. Use this method when you are testing governor limits.
public static Void startTest()
Type: Void
You can also use this method with stopTest to ensure that all asynchronous calls that come after the startTest method are run before doing any assertions or testing. Each test method is allowed to call this method only once. All of the code before this method should be used to initialize variables, populate data structures, and so on, allowing you to set up everything you need to run your test. Any code that executes after the call to startTest and before stopTest is assigned a new set of governor limits.
Marks the point in your test code when your test ends. Use this method in conjunction with the startTest method.
public static Void stopTest()
Type: Void
Each test method is allowed to call this method only once. Any code that executes after the stopTest method is assigned the original limits that were in effect before startTest was called. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs.
Tests the implementation of the InstallHandler interface, which is used for specifying a post install script in packages. Tests run as the test initiator in the development environment.
public static Void testInstall(InstallHandler installImplementation, Version version, Boolean isPush)
- installImplementation: Type: System.InstallHandler A class that implements the
InstallHandlerinterface. - version: Type: System.Version The version number of the existing package installed in the subscriber organization.
- isPush: Type: Boolean (Optional) Specifies whether the upgrade is a push. The default value is
false.
Type: Void
This method throws a run-time exception if the test install fails.
Tests the implementation of the SandboxPostCopy Interface, which is used for specifying a script to run at the completion of a Sandbox copy. Tests run as the test initiator in the development environment.
public static void testSandboxPostCopyScript(System.SandboxPostCopy script, Id organizationId, Id sandboxId, String sandboxName)
-
script: Type: System.SandboxPostCopy A class that implements the
SandboxPostCopyinterface. -
organizationId: Type: Id The sandbox organization ID
-
sandboxId: Type: Id
The sandbox ID to be provided to the SandboxPostCopy script.
-
sandboxName: Type: String The sandbox name to be provided to the SandboxPostCopy script.
Type: void
This method throws a run-time exception if the test install fails.
Salesforce recommends that you use the testSandboxPostCopyScript(script, organizationId, sandboxId, sandboxName, isRunAsAutoProcUser) overload instead of this method. When isRunAsAutoProcUser is true, the SandboxPostCopy script is tested with the same user access permissions as used by post-copy tasks during sandbox creation. Using the same permissions enables the test to better simulate the actual usage of the class, and to uncover potential issues.
See SandboxPostCopy Example Implementation
Tests the implementation of the SandboxPostCopy Interface, which is used for specifying a script to run at the completion of a Sandbox copy. When RunAsAutoProcUser is true, tests run as Automated Process user in the development environment.
public static void testSandboxPostCopyScript(System.SandboxPostCopy script, Id organizationId, Id sandboxId, String sandboxName, Boolean RunAsAutoProcUser)
-
script: Type: System.SandboxPostCopy A class that implements the
SandboxPostCopyinterface. -
organizationId: Type: Id The sandbox organization ID.
-
sandboxId: Type: Id
The sandbox ID to be provided to the SandboxPostCopy script.
-
sandboxName: Type: String The sandbox name to be provided to the SandboxPostCopy script.
-
RunAsAutoProcUser: Type: Boolean When
true, theSandboxPostCopyscript is tested with the same user access permissions as used by post-copy tasks during sandbox creation. Using the same permissions enables the test to better simulate the actual usage of the class, and to uncover potential issues. Whenfalse, the test runs as the test initiator. This option can alter the permissions with which the script is tested, such as the ability to access objects and features.
Type: void
This method throws a run-time exception if the test install fails.
See SandboxPostCopy Example Implementation
Tests the implementation of the UninstallHandler interface, which is used for specifying an uninstall script in packages. Tests run as the test initiator in the development environment.
public static Void testUninstall(UninstallHandler uninstallImplementation)
- uninstallImplementation: Type: System.UninstallHandler A class that implements the
UninstallHandlerinterface.
Type: Void
This method throws a run-time exception if the test uninstall fails.