The following are methods for Test. All methods are static.
public static void clearApexPageMessages()
Type: void
This method may only be used in tests.
@isTest static void clearMessagesTest() { Test.setCurrentPage(new PageReference('/')); ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.WARNING, 'Sample Warning') ); System.assertEquals(1, ApexPages.getMessages().size()); Test.clearApexPageMessages(); System.assertEquals(0, ApexPages.getMessages().size()); }
public static Object createStub(System.Type parentType, System.StubProvider stubProvider)
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.
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.
public static List<Id> enqueueBatchJobs(Integer numberOfJobs)
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.
public static EventBus.TestBroker getEventBus()
Enclose Test.getEventBus().deliver() within the Test.startTest() and Test.stopTest() statement block.
Test.startTest(); // Create test events // ... // Publish test events with EventBus.publish() // ... // Deliver test events Test.getEventBus().deliver(); // Perform validation // ... Test.stopTest();
public static Id getStandardPricebookId()
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.
@isTest public class PriceBookTest { // Utility method that can be called by Apex tests to create price book entries. static testmethod void addPricebookEntries() { // First, set up test price book entries. // Insert a test product. Product2 prod = new Product2(Name = 'Laptop X200', Family = 'Hardware'); insert prod; // Get standard price book ID. // This is available irrespective of the state of SeeAllData. Id pricebookId = Test.getStandardPricebookId(); // 1. Insert a price book entry for the standard price book. // Standard price book entries require the standard price book ID we got earlier. PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId, Product2Id = prod.Id, UnitPrice = 10000, IsActive = true); insert standardPrice; // Create a custom price book Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true); insert customPB; // 2. Insert a price book entry with a custom price. PricebookEntry customPrice = new PricebookEntry( Pricebook2Id = customPB.Id, Product2Id = prod.Id, UnitPrice = 12000, IsActive = true); insert customPrice; // Next, perform some tests with your test price book entries. } }
public static Object invokeContinuationMethod(Object controller, Continuation request)
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.
public static Boolean isRunningTest()
Type: Boolean
public static List<sObject> loadData(Schema.SObjectType sObjectToken, String resourceName)
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.
public static QuickAction.SendEmailQuickActionDefaults newSendEmailQuickActionDefaults(ID contextId, ID replyToId)
Type: SendEmailQuickActionDefaults Class
The default values used for an email message quick action.
public static void setContinuationResponse(String requestLabel, System.HttpResponse mockResponse)
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.
public static void setCreatedDate(Id recordId, Datetime createdDatetime)
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. This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.
@isTest private class SetCreatedDateTest { static testMethod void testSetCreatedDate() { Account a = new Account(name='myAccount'); insert a; Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12)); Test.startTest(); Account myAccount = [SELECT Id, Name, CreatedDate FROM Account WHERE Name ='myAccount' limit 1]; System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12)); Test.stopTest(); } }
public static Void setCurrentPage(PageReference page)
Type: Void
public static Void setCurrentPageReference(PageReference page)
Type: Void
public static Void setFixedSearchResults(ID[] fixedSearchResults)
Type: Void
If opt_set_search_results is not specified, all subsequent SOSL queries return no results.
For more information, see Adding SOSL Queries to Unit Tests.
public static Void setMock(Type interfaceType, Object instance)
Type: Void
public static Void setReadOnlyApplicationMode(Boolean applicationMode)
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.
@isTest private class ApplicationReadOnlyModeTestClass { public static testmethod void test() { // Create a test account that is used for querying later. Account testAccount = new Account(Name = 'TestAccount'); insert testAccount; // Set the application read only mode. Test.setReadOnlyApplicationMode(true); // Verify that the application is in read-only mode. System.assertEquals( ApplicationReadWriteMode.READ_ONLY, System.getApplicationReadWriteMode()); // Create a new account object. Account testAccount2 = new Account(Name = 'TestAccount2'); try { // Get the test account created earlier. Should be successful. Account testAccountFromDb = [SELECT Id, Name FROM Account WHERE Name = 'TestAccount']; System.assertEquals(testAccount.Id, testAccountFromDb.Id); // Inserts should result in the InvalidReadOnlyUserDmlException // being thrown. insert testAccount2; System.assertEquals(false, true); } catch (System.InvalidReadOnlyUserDmlException e) { // Expected } // Insertion should work after read only application mode gets disabled. Test.setReadOnlyApplicationMode(false); insert testAccount2; Account testAccount2FromDb = [SELECT Id, Name FROM Account WHERE Name = 'TestAccount2']; System.assertEquals(testAccount2.Id, testAccount2FromDb.Id); } }
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.
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.
public static Void testInstall(InstallHandler installImplementation, Version version, Boolean isPush)
Type: Void
@isTest static void test() { PostInstallClass postinstall = new PostInstallClass(); Test.testInstall(postinstall, new Version(1,0)); }
public static void testSandboxPostCopyScript(System.SandboxPostCopy script, Id organizationId, Id sandboxId, String sandboxName)
The sandbox ID to be provided to the SandboxPostCopy script.
Type: void
This method throws a run-time exception if the test install fails.
public static Void testUninstall(UninstallHandler uninstallImplementation)
Type: Void
@isTest static void test() { UninstallClass uninstall = new UninstallClass(); Test.testUninstall(uninstall); }