Testing Example – Salesforce.com

As per the limits imposed by salesforce we have a need to create test classes for our code with minimum coverage for 75% of code. So below is the small example to create a test class
To define an Apex method as a ‘test method’, simply define the method as static and add the keyword testMethod. A test method can be defined in any Apex class. A test method can not be defined in an Apex trigger. (Note: Testmethods cannot be called outside of a test context.)
Use the isTest class annotation to define classes that only contain code used for testing your application.
So the two possible ways to create test classes will be
public myTestClass{
static testMethod void myTest() {
//Add your test coverage code here
}
}
Or
@isTest
public myTestClass{
public static void myTest() {
//Add your test coverage code here
}
}
There are times when you need to test large datasets for that there are two keywords Test.startTest and Test.stopTest.These static methods allow a test method to separate the Apex resources and governor limits being used to prepare and initialise the dataset from the resources and limits used during the actual test execution.
Please note always create test data in for each of your test class separately avoid using data from system.
In below we have created a list of 200 accounts and we will
static testMethod void myTest() {
List accounts = new List{};
for(Integer i = 0; i < 200; i++){
Account a = new Account(Name = ‘Test Account ‘ + i);
accounts.add(a);
}
test.startTest();
insert accounts;
test.stoptest();
}
Optionally use the isTest(SeeAllData=true) annotation to grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test didn’t create


Source  :  http://www.saasanalogy.com/testing-example-salesforce-com/

Comments

Popular posts from this blog

Salesforce.com: Expression Operators in Salesforce lightning Components

Custom Calendar on VisualForce Page

Salesforce.com: Scheduled Apex