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 .
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);
}
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 standardcontrollerApexPages.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