Test Class

Contains methods related to Visualforce tests.

Namespace

System

Test Methods

The following are methods for Test. All methods are static.

isRunningTest()

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.

Signature

public static Boolean isRunningTest()

Return Value

Type: Boolean

loadData(Schema.SObjectType, String)

Inserts test records from the specified static resource .csv file and for the specified sObject type, and returns a list of the inserted sObjects.

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.

Return Value

Type: List<sObject>

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.

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

setCurrentPage(PageReference)

A Visualforce test method that sets the current PageReference for the controller.

Signature

public static Void setCurrentPage(PageReference page)

Parameters

page
Type: System.PageReference

Return Value

Type: Void

setCurrentPageReference(PageReference)

A Visualforce test method that sets the current PageReference for the controller.

Signature

public static Void setCurrentPageReference(PageReference page)

Parameters

page
Type: System.PageReference

Return Value

Type: Void

setFixedSearchResults(ID[])

Defines a list of fixed search results to be returned by all subsequent SOSL statements in a test method.

Signature

public static Void setFixedSearchResults(ID[] opt_set_search_results)

Parameters

opt_set_search_results
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 Adding SOSL Queries to Unit Tests.

setMock(Type, Object)

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.

Signature

public static Void setMock(Type interfaceType, Object instance)

Parameters

interfaceType
Type: System.Type
instance
Type: Object

Return Value

Type: Void

Usage

Note
If the code that performs the callout is in a managed package, you must call Test.setMock from a test method in the same package with the same namespace to mock the callout.

setReadOnlyApplicationMode(Boolean)

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.

Signature

public static Void setReadOnlyApplicationMode(Boolean application_mode)

Parameters

application_mode
Type: Boolean

Return Value

Type: Void

Usage

setReadOnlyApplicationMode is available as part of 5 Minute Upgrade. See also the getApplicationReadWriteMode() System method.

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.

@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); } }

startTest()

Marks the point in your test code when your test actually begins. Use this method when you are testing governor limits.

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()

Marks the point in your test code when your test ends. Use this method in conjunction with the startTest method.

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.

Note
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.

testInstall(InstallHandler, Version, Boolean)

Tests the implementation of the InstallHandler interface, used for specifying a post install script in packages. Tests will run as the test initiator in the development environment.

Signature

public static Void testInstall(InstallHandler installImp, Version ver, Boolean isPush)

Parameters

installImp
Type: System.InstallHandler
A class that implements the InstallHandler interface.
ver
Type: System.Version
The version number of the existing package installed in the subscriber organization.
isPush
Type: Boolean
(Optional) Specifies if the upgrade is a push. It’s default value is false.

Return Value

Type: Void

Usage

This method throws a run-time exception if the test install fails.

Example

@isTest static void test() {
  PostInstallClass postinstall = 
    new PostInstallClass();
    Test.testInstall(postinstall, 
      new Version(1,0));
  }

testUninstall(UninstallHandler)

Tests the implementation of the UninstallHandler interface, used for specifying an uninstall script in packages. Tests will run as the test initiator in the development environment.

Signature

public static Void testUninstall(UninstallHandler uninstImp)

Parameters

uninstImp
Type: System.UninstallHandler
A class that implements the UninstallHandler interface.

Return Value

Type: Void

Usage

This method throws a run-time exception if the test uninstall fails.

Example

@isTest static void test() {
  UninstallClass uninstall = 
    new UninstallClass();
    Test.testUninstall(uninstall);
  }
© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.