+ Start a Discussion
Amit Visapurkar 5Amit Visapurkar 5 

How to write test class for the class

public class leadConvert{

public Lead convertLead{get;set;}

    public leadConvert(ApexPages.StandardController controller) {
           
        convertLead = new Lead();        
             
    }  
    
    String leadId = ApexPages.currentPage().getParameters().get('id');
    
    String oppName = '';
     
    String oppC = '';   

    Lead e = [SELECT Id,FirstName,LastName,Opportunity_Name__c,Street__c,City__c,States_Provinces__c,Zip_PostalCode__c,Country__c,Description,DoNotCall,Email,HasOptedOutOfEmail,Fax,HasOptedOutOfFax,LeadSource,MobilePhone,Phone,Title,OwnerId,Lead_Converted__c,Region__c,Enter_State_if_not_able_to_find_above__c,Status,Lead_Record_Type__c FROM Lead WHERE Id=:leadId];

    public pageReference Convert(){ 
       
       boolean sendEmail = convertLead.Send_Email_to_the_Owner__c; 
    
       String baseUrl = URL.getSalesforceBaseUrl().toExternalForm() +'/';

       if(e.Lead_Converted__c == true || e.Status != 'Qualified'){
       
            e.adderror('Lead is either already Converted or Lead Status is not Qualified.');
           
            return null ;
            
       }

       else{
       
        String leadOwnerId = convertLead.Opportunity_Owner__c;

        User leadOwner = [SELECT Id,Email FROM User WHERE Id =: leadOwnerId];
 
        String accId = convertLead.Account__c;
              
        //system.debug('The Owner Id is ' + leadOwnerId);
        
        Account s = [SELECT Id,Name,Description FROM Account WHERE Id=:accId];
        
        String accName = s.Name;
        
        //system.debug('The Account Name is ' + s.Name);

        String OppName = convertLead.Opportunity_Name__c;
        Integer Year = Date.Today().Year();       
        Date OppCloseDate = null;
        
        Opportunity v = new Opportunity();        
        v.AccountId = s.Id;
        v.Name = OppName;
        v.StageName = 'Qualification';
        v.OwnerId = leadOwnerId;
        v.Opportunity_Record_Type__c = e.Lead_Record_Type__c;
        
        List<FiscalYearSettings> Oppfy = [SELECT EndDate,IsStandardYear,StartDate,YearType FROM FiscalYearSettings];
        
        
        if(convertLead.Do_not_create_a_new_Opp_Upon_LeadConvert__c==false){
        
            for(FiscalYearSettings h:Oppfy){
            
                if(h.IsStandardYear == true){
                
                    Date e = h.EndDate;
                    
                    Integer g = e.Year();
                    
                    system.debug('The current year is ' + g);
                    
                        if(g == Year){
                        
                            OppCloseDate = [Select EndDate From Period Where type = 'Quarter' and StartDate = THIS_FISCAL_QUARTER].EndDate;
                        
                        }
                
                }
                
            }
            
            v.CloseDate = OppCloseDate;
            
            insert v;
            
            }
            
            
            system.debug('The Opportunity close date is ' + v.closeDate);
            
            Contact j; 
                      
            List<Contact> leadC = [SELECT Id,AccountId,FirstName,LastName FROM Contact WHERE AccountId=:s.Id AND FirstName=:e.FirstName AND LastName=:e.LastName];
            
            system.debug('The Contacts of account are ' + leadC);
                       
            String param_value = ApexPages.currentPage().getParameters().get('param1');
            
                if(leadC.size()==0){
                                   
                    j = new Contact();
                    
                    j.OwnerId = leadOwnerId;                   
                    j.FirstName = e.FirstName;
                    j.LastName = e.LastName;
                    j.AccountId = s.Id;                    
                    j.Street__c= e.Street__c;
                    j.City__c = e.City__c;
                    j.States_Provinces__c = e.States_Provinces__c;
                    j.Zip_PostalCode__c = e.Zip_PostalCode__c;
                    j.Country__c = e.Country__c;
                    j.Enter_State_if_not_able_to_find_above__c =  e.Enter_State_if_not_able_to_find_above__c;
                    j.Region__c = e.Region__c;                   
                    j.Description= e.Description;
                    j.DoNotCall = e.DoNotCall;                    
                    j.Email = e.Email;                    
                    j.HasOptedOutOfEmail = e.HasOptedOutOfEmail;                    
                    j.Fax = e.Fax;                    
                    j.HasOptedOutOfFax = e.HasOptedOutOfFax;                 
                    j.LeadSource = e.LeadSource;                    
                    j.MobilePhone = e.MobilePhone;                   
                    j.Phone = e.Phone;                    
                    j.Title = e.Title;
                     
                                        
                    insert j;
                    
                    List<Opportunity> leadOpp = [SELECT Id,Name FROM Opportunity WHERE Id=:v.Id];
         
                    if(leadOpp.size() == 0){
         
                         oppName = '';
                         oppC = '';
                     }
         
                    else{
         
                         oppName = leadOpp[0].Name;
                         oppC = leadOpp[0].Id;
         
                    }
                    
                    if(SendEmail == true){
         
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      
                        mail.setToAddresses(new String[] {leadOwner.Email});
                        mail.setReplyTo('avisapurkar@bodhtree.com');            
                        mail.setSenderDisplayName('Goss International');
                        mail.setSubject('A Lead has been converted');                 
                        //mail.setPlainTextBody('Your salesforce.com request to convert a lead into the following records has successfully completed:' );
                        String body = 'Your salesforce.com request to convert a lead into the following records has successfully completed:'+'<br/>'+'<br/>';
                        body += 'Account: '+ s.Name +'<br/>'+'<br/>' ;                                               
                        body += '<a href=' +baseUrl+'/'+s.Id+' >'+baseUrl+s.Id+'</a> <br/><br/>';
                        body += 'Contact : '+ j.FirstName+j.LastName+'<br/><br/>';
                        body += '<a href=' +baseUrl+'/'+j.Id+' >'+baseUrl+j.Id+'</a> <br/><br/>';                       
                        body += 'Opportunity : '+oppName+'<br/>'+'<br/>';
                        body += '<a href=' +baseUrl+'/'+oppC+' >'+baseUrl+oppC+'</a> <br/><br/>';                         
                        body += 'Thank You,'+'<br/>'+'<br/>';
                        body += 'Goss International'+'<br/>'+'<br/>'+'<br/>'+'<br/>';  
                        mail.setHtmlBody(body);

                        Messaging.SendEmailResult[] emailresult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
         
         }
                    
                    e.Lead_Converted__c=true;  
                    
                    update e;              
                                    
                    PageReference pageRef = new PageReference('https://cs20.salesforce.com/'+s.Id);
                    pageRef.setRedirect(true);
                                                                    
                    // Contact fields                 
            
                    return pageRef;

                }
                
                else{   
                 
                        
                        string value = leadC[0].Id;
                        system.debug('The lead Id is ' + value);
                        string url;
                        url = '/apex/LeadContact?param1='+value+'&leadId='+e.Id+'&oId='+leadOwnerId+'&param2='+sendEmail+'&param3='+v.Id; 

                        PageReference pageRef = new PageReference(url);
                        pageRef.setRedirect(true);
            
                        return pageRef;                                 
            
                    } 
                }      
                
           }
                     
}
Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about test classes
1) http://amitsalesforce.blogspot.com/search/label/Test%20Class
2) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Please try below test class.
@isTest 
public class leadConvertTest 
{
	static testMethod void testMethod1() 
	{
	
		Lead lead=new Lead( LastName='Doe',FirstName='John',Company='Test',Status='Qualified' );
		insert lead; 

		Test.StartTest(); 
		
			ApexPages.currentPage().getParameters().put('id', String.valueOf(lead.Id));
			
			ApexPages.StandardController sc = new ApexPages.StandardController(lead);
			leadConvert obj = new leadConvert(sc);
			obj.Convert();

		Test.StopTest();
	}
}

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