Testing Apex


Testing Apex:

Apex provides testing framework that allow you  to write tests,run test,check test results and have code coverage results.

Unit Testing Apex:

  • To facilitate the development of robust, error-free code, Apex supports the creation and execution of unit tests
  • Unit tests are class methods that verify whether a particular piece of code is working properly. 
  • Unit test methods take no arguments, commit no data to the database, send no emails, and are flagged with the testMethod keyword in the method definition.
  • 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
Example:

public class myclass
{
static  testmethod void  mytest()
{
code_block
}
}

@istest:

  • Using the istest annotation to define classes or individual methods that only contain the code  used for testing application.
  • The isTest annotation is similar to creating methods declared as testMethod.

Example:

  A test class that contains two test methods



@isTest

private class MyTestClass {

   // Methods for testing 
    
   @isTest static void test1() {
      // Implement test code 
    
   }

   @isTest static void test2() {
      // Implement test code 
    
   }

}

UNIT TEST LIMITATIONS:

  • Test methods can’t be used to test Web service callouts. Web service callouts are asynchronous, while unit tests are synchronous.
  • You can’t send email messages from a test method.
Since test methods don’t commit data created in the test, you don’t have to delete test data upon completion.


FACTS ABOUT UNIT TEST:

  •  Test methods don’t have access by default to pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access data that they create.
However, objects that are used to manage your organization or metadata objects can still be accessed in your tests such as:
  • User
  • Profile
  • Organization
  • RecordType
  • ApexClass
  • ApexTrigger
  • ApexComponent
  • ApexPage

You can disable this restriction by annotating your test class or test method with the IsTest(SeeAllData=true)annotation.

ISTEST(SEEALLDATA=true) is used whenever we require  to access all organization data ,including standard objects,custom objects,and cutom settings data.


RunAs Method:

  • Generally, all Apex code runs in system mode, and the permissions and record sharing of the current user are not taken into account.
  • The system method runAs enables you to write test methods that change either the user contexts to an existing user or a new user, or to run using the code from a specific version of a managed package.
  • When running as a user, all of that user's record sharing is then enforced. You can only use runAs in a test method.
  • The original system context is started again after all runAs test methods complete.
  • The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses.
Limit Method:

  • The Limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount of heap size remaining.
There are two versions of every method:

  1. The first returns the amount of the resource that has been used in the current context.
  2.  The second version contains the word “limit” and returns the total amount of the resource that is available for that context.
For example, getCallouts returns the number of callouts to an external service that have already been processed in the current context, while getLimitCallouts returns the total number of callouts available in the given context.

STARTTEST METHOD:

  • The startTest method marks the point in your test code when your test actually begins.
  •  Each testMethod 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 startTestand before stopTest is assigned a new set of governor limits.
STOPTEST METHOD:

  • The stopTest method marks the point in your test code when your test ends. 
  • 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.
Adding SOSL QUERIES TO UNIT TESTS:

  • Any Salesforce Object Search Language (SOSL) query that is added to an Apex test method returns an empty set of search results when the test method executes.
  • If you do not want the query to return an empty list of results, you can use the Test.setFixedSearchResults system method to define a list of record IDs that are returned by the search.
Example:

public class SoslFixedResultsTest1 {

    public static testMethod void testSoslFixedResults() {
       Id [] fixedSearchResults= new Id[1];
       fixedSearchResults[0] = '001x0000003G89h';
       Test.setFixedSearchResults(fixedSearchResults);
       List<List<SObject>> searchList = [FIND 'test' 
                                         IN ALL FIELDS RETURNING 
                                            Account(id, name WHERE name = 'test' LIMIT 1)];
    }
}

NOTE:

Although the account record with an ID of 001x0000003G89h may not match the query string in the FIND clause ('test'), the record is passed into the RETURNING clause of the SOSL statement. If the record with ID 001x0000003G89h matches the WHERE clause filter, the record is returned. If it does not match the WHERE clause, no record is returned.


RUNNING UNIT TEST METHODS:

You can run unit tests for:
  • A specific class
  • A subset of classes
  • All unit tests in your organization
To run a test, use any of the following:
  • The Salesforce user interface
  • The Force.com IDE
  • The API

Run test using The Salesforce user interface:

To use the Apex Test Execution page:

  1. Click Your Name | Setup | Develop | Apex Test Execution.
  2. Click Select Tests....
  3. Select the tests to run. The list of tests contains classes that contain test methods
  4. Click Run.



0 comments:

Post a Comment