Newer Version Available
Test Class
Namespace
Test Methods
The following are methods for Test. All methods are static.
calculatePermissionSetGroup(psgId)
Signature
public static void calculatePermissionSetGroup(String psgId)
Parameters
- psgId
- Type: String
- A single ID for a specified permission set group.
Return Value
Type: void
clearApexPageMessages()
Signature
public static void clearApexPageMessages()
Return Value
Type: void
Usage
This method may only be used in tests.
Example
1@isTest
2 static void clearMessagesTest() {
3 Test.setCurrentPage(new PageReference('/'));
4 ApexPages.addMessage(
5 new ApexPages.Message(ApexPages.Severity.WARNING, 'Sample Warning')
6 );
7 System.assertEquals(1, ApexPages.getMessages().size());
8 Test.clearApexPageMessages();
9 System.assertEquals(0, ApexPages.getMessages().size());
10 }createSoqlStub(targetType, soqlStub)
Signature
public static void createSoqlStub(Schema.SObjectType targetType, System.SoqlStubProvider soqlStub)
Parameters
- targetType
- Type: Schema.SObjectType
- The SObject type to be stubbed. This parameter can’t be null.
- soqlStub
- Type: System.SoqlStubProvider
- An implementation of the SoqlStubProvider abstract class.
Return Value
Type: void
createStub(parentType, stubProvider)
Signature
public static Object createStub(System.Type parentType, System.StubProvider stubProvider)
Parameters
- parentType
- Type: System.Type
- The type of the Apex class to be stubbed.
- stubProvider
- System.StubProvider
- An implementation of the StubProvider interface.
Return Value
Type: Object
Returns the stubbed object to use in testing.
Usage
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.
createStubQueryRow(targetType, fieldMapWithRelationshipKeys)
Signature
public static SObject createStubQueryRow(Schema.SObjectType targetType, Map<String,Object> fieldMapWithRelationshipKeys)
Parameters
- 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.
Example
1Map<String, Object> engagement1 = new Map<String, Object> {
2 'id' => '0gj000000000XYZ'
3 };
4Map<String, Object> engagement2 = new Map<String, Object> {
5 'id' => '0gj000000001XYZ'
6 };
7
8engagementMaps.add(engagement1);
9engagementMaps.add(engagement2);
10
11 List<Engagement__dlm> engagements = (List<Engagement__dlm>)
12 Test.createStubQueryRows(Engagement__dlm.SObjectType,
13 engagementMaps);
14
15 Map<String, Object> contactMap = new Map<String, Object> {
16 'id' => '003000000000000',
17 'LastName' => 'Bear',
18 'engagements__r' => engagements
19 };
20
21 Contact obj = (Contact) Test.createStubQueryRow(sobjectType, contactMap);createStubQueryRows(targetType, fieldMapWithRelationshipKeysForMultipleRows)
Signature
public static List<SObject> createStubQueryRows(Schema.SObjectType targetType, List<Map<String,Object>> fieldMapWithRelationshipKeysForMultipleRows)
Parameters
- 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.
Example
1Map<String, Object> engagement = new Map<String, Object> {
2 'id' => '0gjxx0000000XYZ'
3 };
4 Map<String, Object> engagement2 = new Map<String, Object> {
5 'id' => '0gjxx0000001XYZ'
6 };
7
8 engagementMaps.add(engagement);
9 engagementMaps.add(engagement2);
10
11 List<~~ENGAGEMENT_DMO_NAME~~> engagements = (List<~~ENGAGEMENT_DMO_NAME~~>)
12 Test.createStubQueryRows(~~ENGAGEMENT_DMO_NAME~~.SObjectType,
13 engagementMaps);
14
15 Map<String, Object> contactMap = new Map<String, Object> {
16 'id' => '003000000000000',
17 'LastName' => 'Bear',
18 '~~DMO_REL_NAME~~' => engagements
19 };
20
21 Contact obj = (Contact) Test.createStubQueryRows(sobjectType, contactMap);enableChangeDataCapture()
Signature
public static void enableChangeDataCapture()
Return Value
Type: void
Usage
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.
enqueueBatchJobs(numberOfJobs)
Signature
public static List<Id> enqueueBatchJobs(Integer numberOfJobs)
Parameters
- numberOfJobs
- Type: Integer
- Number of test jobs to enqueue.
Usage
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.
getEventBus()
Signature
public static EventBus.TestBroker getEventBus()
Usage
Enclose Test.getEventBus().deliver() within the Test.startTest() and Test.stopTest() statement block.
1Test.startTest();
2// Create test events
3// ...
4// Publish test events with EventBus.publish()
5// ...
6// Deliver test events
7Test.getEventBus().deliver();
8// Perform validation
9// ...
10Test.stopTest();getFlexQueueOrder()
getStandardPricebookId()
Signature
public static Id getStandardPricebookId()
Usage
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.
Example
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.
1@isTest
2public class PriceBookTest {
3 // Utility method that can be called by Apex tests to create price book entries.
4 static testmethod void addPricebookEntries() {
5 // First, set up test price book entries.
6 // Insert a test product.
7 Product2 prod = new Product2(Name = 'Laptop X200',
8 Family = 'Hardware');
9 insert prod;
10
11 // Get standard price book ID.
12 // This is available irrespective of the state of SeeAllData.
13 Id pricebookId = Test.getStandardPricebookId();
14
15 // 1. Insert a price book entry for the standard price book.
16 // Standard price book entries require the standard price book ID we got earlier.
17 PricebookEntry standardPrice = new PricebookEntry(
18 Pricebook2Id = pricebookId, Product2Id = prod.Id,
19 UnitPrice = 10000, IsActive = true);
20 insert standardPrice;
21
22 // Create a custom price book
23 Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
24 insert customPB;
25
26 // 2. Insert a price book entry with a custom price.
27 PricebookEntry customPrice = new PricebookEntry(
28 Pricebook2Id = customPB.Id, Product2Id = prod.Id,
29 UnitPrice = 12000, IsActive = true);
30 insert customPrice;
31
32 // Next, perform some tests with your test price book entries.
33 }
34}invokeContinuationMethod(controller, request)
Signature
public static Object invokeContinuationMethod(Object controller, Continuation request)
Parameters
- 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.
Return Value
Type: Object
The response of the continuation callback method.
Usage
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.
isRunningTest()
Signature
public static Boolean isRunningTest()
Return Value
Type: Boolean
isSoqlStubDefined(targetType)
Signature
public static Boolean isSoqlStubDefined(Schema.SObjectType targetType)
Parameters
- targetType
- Type: Schema.SObjectType
- The SObject type to check. This parameter can’t be null.
Return Value
Type: Boolean
loadData(sObjectToken, resourceName)
Signature
public static List<sObject> loadData(Schema.SObjectType sObjectToken, String resourceName)
Parameters
- 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.
Usage
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.
newSendEmailQuickActionDefaults(contextId, replyToId)
Signature
public static QuickAction.SendEmailQuickActionDefaults newSendEmailQuickActionDefaults(ID contextId, ID replyToId)
Parameters
Return Value
Type: SendEmailQuickActionDefaults Class
The default values used for an email message quick action.
setContinuationResponse(requestLabel, mockResponse)
Signature
public static void setContinuationResponse(String requestLabel, System.HttpResponse mockResponse)
Parameters
- 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.
Return Value
Type: void
Usage
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.
setCreatedDate(recordId, createdDatetime)
Signature
public static void setCreatedDate(Id recordId, Datetime createdDatetime)
Parameters
Return Value
Type: void
Usage
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.
1@isTest
2private class SetCreatedDateTest {
3 static testMethod void testSetCreatedDate() {
4 Account a = new Account(name='myAccount');
5 insert a;
6 Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
7 Test.startTest();
8 Account myAccount = [SELECT Id, Name, CreatedDate FROM Account
9 WHERE Name ='myAccount' limit 1];
10 System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));
11 Test.stopTest();
12 }
13}setCurrentPage(page)
Signature
public static Void setCurrentPage(PageReference page)
Parameters
- page
- Type: System.PageReference
Return Value
Type: Void
setCurrentPageReference(page)
Signature
public static Void setCurrentPageReference(PageReference page)
Parameters
- page
- Type: System.PageReference
Return Value
Type: Void
setFixedSearchResults(fixedSearchResults)
Signature
public static Void setFixedSearchResults(ID[] fixedSearchResults)
Parameters
- 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 WHERE or LIMIT clauses. If these clauses exist in the SOSL queries, they are applied to the list of fixed search results.
Return Value
Type: Void
Usage
If opt_set_search_results is not specified, all subsequent SOSL queries return no results.
For more information, see Dynamic SOSL.
setMock(interfaceType, instance)
Signature
public static Void setMock(Type interfaceType, Object instance)
Parameters
- interfaceType
- Type: System.Type
- instance
- Type: Object
Return Value
Type: Void
Usage
setReadOnlyApplicationMode(applicationMode)
Signature
public static Void setReadOnlyApplicationMode(Boolean applicationMode)
Parameters
- applicationMode
- Type: Boolean
Return Value
Type: Void
Usage
Also see the getApplicationReadWriteMode() System method.
Do not use setReadOnlyApplicationMode for purposes unrelated to Read-Only Mode testing, such as simulating DML exceptions.
Example
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.
1@isTest
2private class ApplicationReadOnlyModeTestClass {
3 public static testmethod void test() {
4 // Create a test account that is used for querying later.
5 Account testAccount = new Account(Name = 'TestAccount');
6 insert testAccount;
7
8 // Set the application read only mode.
9 Test.setReadOnlyApplicationMode(true);
10
11 // Verify that the application is in read-only mode.
12 System.assertEquals(
13 ApplicationReadWriteMode.READ_ONLY,
14 System.getApplicationReadWriteMode());
15
16 // Create a new account object.
17 Account testAccount2 = new Account(Name = 'TestAccount2');
18
19 try {
20 // Get the test account created earlier. Should be successful.
21 Account testAccountFromDb =
22 [SELECT Id, Name FROM Account WHERE Name = 'TestAccount'];
23 System.assertEquals(testAccount.Id, testAccountFromDb.Id);
24
25 // Inserts should result in the InvalidReadOnlyUserDmlException
26 // being thrown.
27 insert testAccount2;
28 System.assertEquals(false, true);
29 } catch (System.InvalidReadOnlyUserDmlException e) {
30 // Expected
31 }
32 // Insertion should work after read only application mode gets disabled.
33 Test.setReadOnlyApplicationMode(false);
34
35 insert testAccount2;
36 Account testAccount2FromDb =
37 [SELECT Id, Name FROM Account WHERE Name = 'TestAccount2'];
38 System.assertEquals(testAccount2.Id, testAccount2FromDb.Id);
39 }
40}startTest()
Signature
public static Void startTest()
Return Value
Type: Void
Usage
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.
stopTest()
Signature
public static Void stopTest()
Return Value
Type: Void
Usage
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.
testInstall(installImplementation, version, isPush)
Signature
public static Void testInstall(InstallHandler installImplementation, Version version, Boolean isPush)
Parameters
- installImplementation
- Type: System.InstallHandler
- A class that implements the InstallHandler interface.
- 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.
Return Value
Type: Void
Example
1@isTest static void test() {
2 PostInstallClass postinstall =
3 new PostInstallClass();
4 Test.testInstall(postinstall,
5 new Version(1,0));
6 }testSandboxPostCopyScript(script, organizationId, sandboxId, sandboxName)
Signature
public static void testSandboxPostCopyScript(System.SandboxPostCopy script, Id organizationId, Id sandboxId, String sandboxName)
Parameters
- script
- Type: System.SandboxPostCopy
- A class that implements the SandboxPostCopy interface.
- 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.
Return Value
Type: void
Usage
This method throws a run-time exception if the test install fails.
Example
testSandboxPostCopyScript(script, organizationId, sandboxId, sandboxName, RunAsAutoProcUser)
Signature
public static void testSandboxPostCopyScript(System.SandboxPostCopy script, Id organizationId, Id sandboxId, String sandboxName, Boolean RunAsAutoProcUser)
Parameters
- script
- Type: System.SandboxPostCopy
- A class that implements the SandboxPostCopy interface.
- 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, 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.
- When false, 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.
Return Value
Type: void
Usage
This method throws a run-time exception if the test install fails.
Example
testUninstall(uninstallImplementation)
Signature
public static Void testUninstall(UninstallHandler uninstallImplementation)
Parameters
- uninstallImplementation
- Type: System.UninstallHandler
- A class that implements the UninstallHandler interface.
Return Value
Type: Void
Example
1@isTest static void test() {
2 UninstallClass uninstall =
3 new UninstallClass();
4 Test.testUninstall(uninstall);
5 }