Salesforce Test Class

Apex Unit Tests

test class simply refers to the input required to confirm if instructions and methods used in developing an application or program are working correctly in delivering the desired output.

Apex unit tests ensure high quality for your Apex code and let you meet requirements for deploying Apex.

Code Coverage Requirement for Deployment

Before you can deploy your code, at least 75% of Apex code must be covered by tests, and all those tests must pass. In addition, each trigger must have some coverage. Even though code coverage is a requirement for deployment, don’t write tests only to meet this requirement. Make sure to test the common use cases in your app, including positive and negative test cases, and bulk and single-record processing.

Test Method Syntax

@isTest static void testName() { // code_block }

Using the isTest annotation instead of the testMethod keyword is more flexible as you can specify parameters in the annotation.

Test classes can be either private or public. If you’re using a test class for unit testing only, declare it as private. Public test classes are typically used for test data factory classes

 

Here We will Learn how to Write Test class from Zero level and after reading the complete blog you will be the hero of a test class.

Mandatory things need to be used in the test class.

For Apex Controller

  • @IsTest -Anotation of Test class  (Mandatory)
  • TestMethod- Test class Method (Mandatory)
  • ApexclassName apx =new ApexclassName();(Mandatory)

ApexclassName-apex class name

 

Example

Test Class For Apex Controller

Controller

Test Class

@IsTest

Public class MycontrollerTectclass

{
Public static TestMethod Void Updatevalue(){ //Test mtehod

//………Functionality
MyController con=new MyController(); //Apex Controller name
con.main(); //method name
}
}

Test Class For Controller With Visualforce Page

Controller

Public class MyController
{
Public list<account> acc{get;set;}
public string str;
Public MyController(){
acc=new list<account>();
str=Apexpages.currentpage().getparameters().get(‘id’);
}
Public void main()
{
acc=[Select Id,Name,Industry,Amount from Account where id=:str];
}
}
}

TestClass

@isTest
public class MyControllerTestClass
{
static testMethod void testMethod1()
{
Account Acc= new Account();
Acc.Name=’Test Account record’ ;
insert Acc;

Test.StartTest();

PageReference pageRef = Page.AccountUI; // Add your VF page Name here
pageRef.getParameters().put(‘id’, String.valueOf(Acc.Id));
Test.setCurrentPage(pageRef);

myController con= new myController();

con.main(); call all your function here
Test.StopTest();
}
}

Test Class For Extension Controller

Controller

Public class MyController
{
Public list<account> acc{get;set;}
public string str;
Public MyController(Apexpages.StandardController Cont)
{
acc=new list<account>();
str=Apexpages.currentpage().getparameters().get(‘id’);
}

Public void main()
{
acc=[Select Id,Name,Industry,Amount from Account where id=:str];
}
}
}

Test Class:

@isTest
public class MycontrollerTestClass
{
static testMethod void testMethod1()
{
Account acc= new Account();
acc.Name=’Test Account record’ ;
insert acc;

Test.StartTest();
ApexPages.StandardController sc = new ApexPages.StandardController(acc);
myController conex= new myController(sc);

PageReference pageRef = Page.AccountUI; // Add your VF page Name here
pageRef.getParameters().put(‘id’, String.valueOf(acc.Id));
Test.setCurrentPage(pageRef);

conex.main(); call all your function here
Test.StopTest();
}
}

Test Class For Wrapper class 

Controller:

public with sharing class WrapperController {
public class WrapperClass {
public String name {get; set;}
}
}

Test Class:

@isTest
private class TestWrapperController {
public static void myUnitTest(){
WrapperController .WrapperClass wrapper= new WrapperController .WrapperClass ();
wrapper.name = ‘Test Wrapper’;
}
}

Test Class For Controller Using Webservice and HTTP callout

If you are using HTTP Callout then Mock class is must

Mock Class For Webservice Callout

global with sharing class ExportCodeCoverageMock implements HTTPCalloutMock{
global HTTPResponse respond(HTTPRequest req){
HttpResponse res = new HTTPResponse();
res.setHeader(‘Content-Type’, ‘application/JSON’);
res.setBody(‘Your body’);
res.setStatusCode(201);
return res;
}
}

Call Mock class to Test class

@IsTest
Private class ExportExcelTestCoverageController_Test{
@IsTest
static void CoverageTest()
{
 Test.setMock(HttpCalloutMock.class, new ExportCodeCoverageMock ());//Mock class

MyController.Attributes testWrap=new MyController.Attributes(); //Function name

testWrap3.records= new list<MyController.Records>();
//testWrap3.records= testWrap1;
PageReference pageRef1 = Page.MyControllervfpage; //Visualforce page name
Test.setCurrentPage(pageRef1);

}

}

 

Test class best practice

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if the class version is more than 25

2. Test environment support @testVisible, @testSetUp as well
3. A unit test is to test a particular piece of code working properly or not.
4. Unit test method takes no argument, commit no data to the database, send no email, flagged with the testMethod keyword.
5. To deploy to production at-least 75% code coverage is required
6. System. debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the percentage of code coverage, we should make sure that every use case should be covered including positive, negative, bulk and single record.
Single Action -To verify that the single record produces the correct an 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 correct data and not go past the limit.
Negative Testcase: -Not to add future date, Not to specify the negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can’t be a interface or enum .
15. Test method code can’t be invoked by non test request .
16. Stating with Salesforce API 28.0 test method cannot reside inside non-test classes.
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method cannot be used to test web-service call out. Please use callout mock.
19. You can’t  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass,
ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,’ResourceName’).
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. The maximum number of test classes run per 24 hour of period is  not greater of 500 or 10 multiplication of test classes of your organization.
27. 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 .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .

For More details visit www.Dreamstel.com

 

Advertisements