Thursday 4 June 2015

Salesforce Testing Best Practice Guidelines | Unit Test Mechanism in Salesforce | Test Methods


Unit Test Mechanism in Salesforce

1) Single action

Test to verify that a single record produces the correct, expected result. So created the unit test data in your test class.

2) Bulk actions

Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only the single record case, but the bulk cases as well.

3) Restricted user

Test whether a user with restricted access to the sObjects used in your code sees the expected behavior. That is, whether they can run the code or receive error messages. Always use RunAs for to check user access on sObjects.

4) Positive behaviour

Test to verify that the expected behaviour occurs through every expected permutation, that is, that the user filled out everything correctly and did not go past the limits.

5) Negative behaviour

There are likely limits to your applications, such as not being able to add a future date, not being able to specify a negative amount, and so on. You must test for the negative case and verify that the error messages are correctly produced as well as for the positive, within the limits cases.

Test Methods

1) Apply testMethod or @isTest to methods

      • Demarcates a single self-contained test

public class MyClass 
{
  @isTest  
    private static void myTest() 
   {
      // code block
   }
}


2) Apply @isTest to classes

• Optional: test methods may also be contained in public classes
• Won’t count against the 2MB/org Apex code limit
– @isTest methods will not be shown in code coverage results
• The class must be marked as private
• Public methods can’t be called from outside the class


@isTest 
private class MyTestClass 
{
   @isTest private static void myTest() 
   {
 // code block
   }
}




Apex tests will not:

  1.  Commit changes to the database.
  2.  But SOQL queries will find records created during the test.
  3.  Perform callouts to external Web services.
  4.  Send outbound email.
  5.  Return results from SOSL searches.

Test Requirements in Production
  1. 75% of Apex statements must be executed (strive for 100% code coverage)
  2. All Apex triggers must be called. 
  3. All Apex tests must execute without throwing any uncaught exceptions or exceeding governors.


Step 1: Positive Path

Verify that when passed valid inputs, called code completes without throwing an exception.

Step 2: End state
  • Verify data-defined outcomes with assertions
  • System.assert()
  • System.assertEquals()
  • System.assertNotEquals()

Step 3: Negative Path

Verify that when passed invalid inputs, exceptions are properly handled

Step 4: Governors
  • Verify that code is bulk ready.
  • Pass up to 200 records.
  • Trade-off between test performance and effectiveness


Please let us know if this post will help you.


Thanks,
Amit Chaudhary


No comments:

Post a Comment