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
amit wagaskaramit wagaskar 

how to write test class for below apex controller class...???

HI All,
 I am new to salesforce and wants to know how to write a test class for below apex controller class
//controller class
public class myWeb2LeadExtension {

    private final Lead weblead;
    private ID Leadid;
   
    public myWeb2LeadExtension(ApexPages.StandardController
                                stdController) {
       this.weblead = (Lead)stdController.getRecord();
       this.Leadid    = stdController.getId();
                                     
    }
    
    private Attachment myfile;
    public Attachment getmyfile() {
    myfile = new Attachment();
    return myfile;
}

   
     public PageReference saveLead() {
       try {
        weblead.LeadSource='Job Application Non India';
        weblead.Company='added from Job Application Page';
        weblead.Status='open';
        insert(weblead);
        Attachment a = new Attachment(parentid=weblead.id, Name = myfile.name , Body = myfile.Body );
        insert a;
        
           
        
       }
       catch(System.DMLException e) {
           ApexPages.addMessages(e);
           return null;
       }
         
         
       PageReference p = Page.ThankYou;
       p.setRedirect(true);
       return p;
     }
    
    
    
}
thanks in advance,
Amit wagaskar
Best Answer chosen by amit wagaskar
Maharajan CMaharajan C
Hi Amit,

One Small change Apex Class:
  @TestVisible  private Attachment myfile;     //// Add the @TestVisible in Private then only it will be visible to test class.

Try the below test class:

@isTest
public class myWeb2LeadExtensionTest {

static testmethod void saveLeadtest()
{
Lead ld = new Lead(LastName='Test Lead',Email='Testemail@test.com',Company='Test Company');
Blob b = Blob.valueOf('Test Data');
Attachment attachment = new Attachment();
attachment.Name = 'Test Attachment for Parent';
attachment.Body = b;

PageReference pageRef = Page.ThankYou ;
Test.setCurrentPage(pageRef);

ApexPages.StandardController stc = new ApexPages.StandardController(ld);
myWeb2LeadExtension weblead = new myWeb2LeadExtension(stc);
weblead.myfile = attachment;
weblead.getmyfile();
weblead.saveLead();
}
}

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
Maharajan.C