Wednesday 3 June 2015

Tips and Tricks For Test Class

Why we  need to write test class ? Some people will answer like we need code coverage to deploy code to production, as we don't have right to write code in production directly  . Yes it is correct but not 100 percent  .Test class  basically helps us to test our functionality of code which is important to develop  a better application . So we should not concentrate only code coverage though it is required  .
We should write proper test case to test all types of scenario . We should not happy with 75 % code coverage ,we should try to achieve 100 % coverage with all test scenario like  positive ,negative and bulk unit test .


Below points we should know as a developer :-

  • Test class must start with @isTest annotation if class class version is more than 25
  • Test environment support @testVisible, @testSetUp as well
  • Unit test is to test particular piece of code working properly or not .
  • Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
  • To deploy to production at least 75% code coverage is required and al test case should pass .
  • System.debug statement are not counted as a part of apex code coverage .
  • Test method and test classes are not counted as a part of code coverage .
  • We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative, bulk and single record .
  • Single Action -To verify that the the single record produces the correct and expected result .
  • Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
  • Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
  • Negetive Testcase :-Not to add future date ,Not to specify negative amount.
  • .Restricted User :-Test whether a user with restricted access used in your code .
  • .Conditional and ternary operator are not considered executed unless both positive and negative branches are executed .
  • Unit test are class methods that verify whether a particular piece of code is error free or not .
  • Test class should be annoted with isTest .
  • isTest annotation with test method  is equivalent to  testMethod keyword .
  • Test method should static and no void return type .
  • Test class and method default access is private ,no matter to add access specifier .
  • Classes with isTest annotation can't be a interface or enum .
  • Test method code can't be invoked by non test request .
  • Stating with salesforce API 28.0 test method can not reside inside non test classes .
  • @Testvisible annotaion to make visible private methods inside test classes.
  • Test method can not be used to test webservice call out .Instaed use call out mock .
  • You cann't  send email fron test method.
  • User,profile,organisation,AsyncApexjob,Corntrigger,RecordType,ApexClass,ApexComponent,ApexPage we can access without (seeAllData=true) .
  • SeeAllData=true will not work for API 23 version eailer .
  • Acessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
  • Create Test Factory class with isTest annotation to exclude from organization code size limit .
  • @testSetup to create test records once in a method  and use in every test method in the test class .
  • We can run unit test for a specific class, set of classes and all classes .
  • We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
  • Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
  • As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
  • System.runAs will not enforce user permission or field level permission .
  • Every test to runAs count against the total number of DML issued in the process . 

Below code snippet help you to start writing test class :-

Test class definition :-
Sample 1-
@isTest
private class MyTestClass {}
Sample 2-Grant test classes to  access  all data in the organization.
@isTest(SeeAllData=true)
private class MyTestClass {}
Sample 3: Specify whether test class execute during package installation or not 
@isTest(OnInstall=true/flase)
private class MyTestClass {}
Test method definition :- Sample 1-with testmethod keyword . static testMethod void testName() { // code_block } Sample 2:-Here we can avoid testMethod with @isTest annotation which will help us to get benifit of parameters indivisually incase not there in class level . @isTest static void testName() { // code_block }

Below tips  helps us to move towards 100 % code coverage :-

1.Tips for standardcontroller

ApexPages.standradController con=ApexPages.StandradController(Needs to pass the instance of the standard/Custom Object);

2.StandardSetcontroller

ApexPages.standradSetController con=ApexPages.StandradSetController(Needs to pass the list of the standard/Custom Object);

3.For wrapper class

ClassName.WrapperclassName wrp=new ClassName.WrapperclassName();

4.Test code catch block .

We need to create a excption in test method to cover .We can do in two different ways one suppose we want an excption on update .we can do like below .

 Trick 1-

Account acc =new Account();
try{
  insert/update acc;
}catch(Exception ex){}
As mandatory fields are missing it will throw exception and it will cover the catch block .
Trick 2-We need to add two line  of code in class like below .
try{
   DML statement;
if(Test.isRunningTest())
Integer intTest =20/0;
} catch(Exception ex){
ApexPages.Message msg = new              ApexPages.Message(ApexPages.Severity.error,qe.getMessage());
ApexPages.addMessage(msg);
}
     
There is a class named Test in apex which has some method which help us to write some useful test case   Test class method




Batch Apex in Depth

Basics of batch apex :-

Apex class that implements the Database.Batchable Interface is known as batch class .
We are basically using batch apex to avoid some governor limits .
There are two interface in  Database Namespace .
1.Batchable
Below are methods in Batchable interface
Public System.Iterable start(Database.BatchabelContext bcon)
Public Database.QueryLocator start(Database.BatchabelContext bcon)
Public void execute(Database.BatchableContext bc,List<Sobject> scope)
Public void finish(Database.BatchableContext bc)
2.BatchableContext
Below are the methods in the interface
 Public Id getJobId()
 public Id getChildJobId()
Basic thing is that once you will implement Batchable interface in your class you have to implement three methods in that interface .

Flow is that when you execute your class start method will execute once and return a list in two different form as we have two types of return type in start method .
The list which will return from the start method will available in execute methods scope execute method will execute according to your batch size .
Assume that you have 1000 record ,if you set your batch size as 100 then your execute method will execute 10 times .
Finally the finish method will execute once the execute method will complete the execution .
Basically in the signature of all method one common parameter we are passing named BatchabelContext, this is to get the batch  JobId and childJobId .
Both method returns the id of  "AsyncApexJob" object record , where  both have self relationship and child record will have different type and contain the last executed record id .

How to write simple  batch class :-

Below example will help you to update all account name with post fix as UpdatedbatchApex .
Here start method will return a list of account which will pass to the scope of execute method ,scope size will depends on your batch size which you will defined while executing the batch class . 

  global class AccountUpdateBatch implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'SELECT Id,Name FROM Account';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Account> scope){
         for(Account acc : scope){
             acc.Name = acc.Name +'UpdatedByBatch';            
         }
         update scope;
    }   
    global void finish(Database.BatchableContext BC){ }
}

How to execute the batch apex :-
In Database class there are two static method
executeBatch(Instance Of class )
excecuteBatch(InstanceOf batch class ,batchsize )

If you want to defined any limit of record to pass into execute method per execution then you need to use second method .Batch size can very from 1-2000.
If you will call first method then it will take the default batch size as 200.

Batch Apex Governor Limits:-
  • All methods in the class must be defined as global or public.
  • Up to 5 batch jobs can be queued or active concurrently.
  • In a running test, you can submit a maximum of 5 batch jobs.
  • The maximum number of batch Apex method executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater.
  • You cannot use the getContent and getContentAsPDF PageReference methods in a batch job.
  • The start, execute, and finish methods can implement up to 10 callouts each.
  • In a running test, you can submit a maximum of 5 batch jobs.
  • A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.
  • Start method can have up to 15 query cursors open at a time per user.
  • Execute and finish methods each have a limit of five open query cursors per user.