function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
renu anamalla 9renu anamalla 9 

How to write the test cases ..please give me example

Take 1 class & write Test class
Amit Chaudhary 8Amit Chaudhary 8
Please check below post for test class example
1) http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html
2) https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

Please check above post code level example

Please check below post to learn about test classes in salesforce
1) http://amitsalesforce.blogspot.in/search/label/Test%20Class
2) http://amitsalesforce.blogspot.in/2015/09/test-classes-with-istest.html
3) http://amitsalesforce.blogspot.in/2015/06/salesforce-testing-best-practice.html

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with 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 covered including positive, negative,bulk and single record .
Single Action -To verify that the 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 correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify 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 can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out 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. 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.
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 .


Please let us know if this post will help you

Thanks
Amit Chaudhary
DeepthiDeepthi (Salesforce Developers) 
Hi Renu,

A 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. 
Important considerations:
  • Use the @isTest annotation.
  • The test class starts its execution from the "testMethod". 
  • Cover as many lines as possible. 
  • At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
  • Use System.assert methods to prove that code behaves properly.
  • Set up test data:
    • Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization.
    • Create all test data before calling the Test.startTest method.
    • Since tests don't commit, you won't need to delete any data.
  • Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the expected outcome, and so on.
  • Test the classes in your application individually. Never test your entire application in a single test.

Please refer the links below for more reference.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm 

http://rainforce.walkme.com/how-to-write-test-class-in-salesforce/ 

Hope this helps you!
Best Regards,
Deepthi
JyothsnaJyothsna (Salesforce Developers) 
Hi Renu,

 Test class are allowed to create test methods whether your functionality is working or not.
In Salesforce Test classes are very important to deploy your code to PRODUCTION.
You need to cover at least 75% ( Average coverage of all classes) code coverage by using test methods in Salesforce to deploy your classes to PRODUCTION.

Here I will explain how to write test class. First, write a simple Apex class 

Apex Class:
 
public Class CreatingAccount
{
public Account createAccount(String name)  //method to create account
{
Account acc = new Account();
acc.Name = name;
return acc;
}
}

Above class is to create/insert new account. This is a simple example to create an apex class.

Test Class:
 
@isTest
public class CreateAccountTest
{
  static testMethod void testInsertAccount()
  {
  CreatingAccount ca = new CreatingAccount();
  ca.createAccount(‘TestclassAcc1’);
  
  }
}

Above class is a simple test class. Which covers the code for above defined class.
 Now how can know percentage covered by 'mytest' class to my main Apex Class?
After saving your test class, you will get a button called Run Test. Click on that button, and your test class will run.
To see percent code coverage go to you main class and see the percentage

Test class for Trigger:

Please check the below link 
https://teachmesalesforce.wordpress.com/category/code-sample/

Test class for controller

http://amitsalesforce.blogspot.sg/2015/06/best-practice-for-test-classes-sample.html

Best Practices of Test class
https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

http://www.jitendrazaa.com/blog/salesforce/apex/faq-writing-test-class-in-salesforce/

Please check the below links for more details on test classes

http://www.tutorialspoint.com/apex/apex_testing.htm


Hope this helps you!
Best Regards,
Jyothsna
Ajay K DubediAjay K Dubedi
Hi Renu,

Manual Test Cases OR Test Class for any Apex Trigger, Apex Class it completely depends upon the Business Requirement. 
You need to cover at least 75% Average coverage of your code in Salesforce to deploy your classes to PRODUCTION.
Apex class:
public class AccountCreation {
    public static void newAccountRecords() {
        try{
        List<Account> accList= new List<Account>();
        for( Integer i=0 ; i<20 ; i++ ) {
            Account acc=new Account();
            acc.Name = 'Anuj'+i;
            acc.AccountNumber = '12345'+i;
            acc.Fax = '123cloudanalogy';
            acc.Phone = '992211'+i;
            acc.Website='https://trailhead.salesforce.com/content/learn/modules/app-development-without-limits/app-development-without-limits-rate';
            accList.add(acc);
        }
        if(accList.size() > 0) {
            insert  accList;
        }
    }
    catch(Exception ex){
        system.debug('Exception_Line_No--->'+ex.getLineNumber());
        system.debug('Exception_Message--->'+ex.getMessage());
    }
    }
}
Test Class:
@IsTest
public class Test_AccountCreation {
@IsTest
    private static void testAccount(){
        AccountCreation.newAccountRecords();
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
 
Ravi Jangid 7Ravi Jangid 7
Hello developers,

I want test class of this class can anyone provide me test class of this class.

//My Apex Class, Please provide me test class.


global class InvoiceBatchClass implements Database.Batchable <sObject>{
    
    //Variables of Batch Class
    DateTime dt = datetime.now();
    String currentMonth = dt.format('MMMM');
    String currentYear = dt.format('YYYY');

    //Start Method
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([SELECT Id, createdDate, accountId 
                        FROM Contact 
                        WHERE Id NOT IN(SELECT Contact__c FROM Invoice__c) 
                        AND accountId != NULL
                        AND createdDate = THIS_YEAR 
                        AND createdDate = THIS_MONTH]);
    }
    
    //Execute Method
    global void execute(Database.BatchableContext bc, List<Contact> contactList) {
        List <Invoice__c> invoiceList = new List <Invoice__c> ();   
        for(Contact OBJ : contactList) {
            invoiceList.add(new Invoice__c(Month__c = currentMonth, Year__c = currentYear, Account__c = OBJ.AccountId , Contact__c = OBJ.Id,                   Amount__c = 1000));                                 
        }
        System.debug('month : '+currentMonth);
        INSERT invoiceList;
    }
    
    //Finish Method
    global void finish(Database.BatchableContext bc) {
         //Nothing doing
    }
}
Cheekati UsharaniCheekati Usharani
can anyone help me to create test class for this apex class?


 public class VF_GoogleCalloutResponseDataWrapper {

public class Address_components {
public String long_name;
public String short_name;
public List<String> types;
}

public class Geometry {
public Bounds bounds;
public Northeast location;
public String location_type;
public Bounds viewport;
}

public List<Results> results;
public String status;

public class Results {
public List<Address_components> address_components;
public String formatted_address;
public Geometry geometry;
public String place_id;
public List<String> types;
}

public class Bounds {
public Northeast northeast;
public Northeast southwest;
}

public class Northeast {
public Double lat;
public Double lng;
}