0

I have write this class in Salesforce but not able write test class. Please anybody can help me to write test class.

public without sharing class CustomizedReportController{
    public String selectedReportID {get;set;}
    public String additionalEmails {get;set;}
    public Contact reportWrapper {get;set;}

    public String bgColor {public get; public set;}
    public String borderColor {public get; public set;}
    public String fontColor {public get; public set;}
    public String colHeaderColor {public get; public set;}
    public String styleBackgroundTemplate { public get; public set; }

    public boolean editStyle {get;set;}

    private Map<String, String> mapReports;

    public CustomizedReportController() {
      additionalEmails = '';
        mapReports = new Map<String, String>();
        reportWrapper = new Contact();
        if(ApexPages.currentPage().getParameters().containsKey('reportId')){
            selectedReportID = ApexPages.currentPage().getParameters().get('reportId');            
        }
        editStyle = false;
        initDefaultTheme();
        updateReportWrapper();        
        styleBackgroundTemplate = 'background: #START_COLOR;';
        styleBackgroundTemplate += 'background: -moz-linear-gradient(top, #START_COLOR 0%, #END_COLOR 100%);';
        styleBackgroundTemplate += 'background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#START_COLOR), color-stop(100%,#END_COLOR));';
        styleBackgroundTemplate += 'background: -webkit-linear-gradient(top, #START_COLOR 0%,#END_COLOR 100%);';
        styleBackgroundTemplate += 'background: -o-linear-gradient(top, #START_COLOR 0%,#END_COLOR 100%);';
        styleBackgroundTemplate += 'background: -ms-linear-gradient(top, #START_COLOR 0%,#END_COLOR 100%);';
        styleBackgroundTemplate += 'filter: progid:DXImageTransform.Microsoft.gradient(startColorStr=\'#START_COLOR\', EndColorStr=\'#END_COLOR\');';
    }

    private void initDefaultTheme(){
        bgColor = 'FFFFFF';
        borderColor = '000000';
        fontColor = '000000';
        colHeaderColor = '000000';        
    }

    public PageReference updateEditStyle(){
      editStyle = true;
      return null;
    }

    public List<SelectOption> getAllReports() {
      List<SelectOption> lstOption = new List<SelectOption>();
      lstOption.add(new SelectOption('','----None----'));
      for(Report report :  [SELECT Id,Name FROM Report WHERE Format='Tabular' Order By Name Limit 100]) {
        lstOption.add(new SelectOption(String.valueOf(report.Id).substring(0,15),report.Name));
        mapReports.put(String.valueOf(report.Id).substring(0,15),report.Name);
      }
      return lstOption;  
    }

    public pageReference updateReportWrapper(){
      if(selectedReportID != null && selectedReportID != ''){

        List<Contact> lstreportWrap = new List<Contact>([SELECT Id, Name, email, 
        FirstName, LastName,MobilePhone,Phone,Level__c,Title
        FROM Contact WHERE Id = :selectedReportID]);

        if(lstreportWrap.size() > 0){
          reportWrapper = lstreportWrap[0];
          bgColor = lstreportWrap[0].Background_Color__c;
          borderColor = lstreportWrap[0].Border_color__c;
          fontColor = lstreportWrap[0].Font_Color__c;
          colHeaderColor = lstreportWrap[0].Column_Header_Color__c;
        }
        else{
          reportWrapper = new Contact ();          
        }
        if(reportWrapper != null){
          if(reportWrapper.Report_Header__c == null){
            //reportWrapper.Report_Header__c = mapReports.get(selectedReportID);
          }
          if(reportWrapper.Report_Title__c == null){
            reportWrapper.Report_Title__c = '<span style="font-weight:bold;font-size:22px;">'+mapReports.get(selectedReportID)+'</span>';
          }
          if(reportWrapper.Report_Footer__c == null){
            reportWrapper.Report_Footer__c = mapReports.get(selectedReportID);
          } 
        }
      }
      else{      
        reportWrapper = new Contact ();
      }
      return null;
    }

    public PageReference saveData(){
     if(selectedReportID != null && selectedReportID.trim() != ''){
       reportWrapper.FirstName = bgColor;
       reportWrapper.LastName = borderColor;       
       reportWrapper.Font_Color__c = fontColor;
       reportWrapper.Column_Header_Color__c = colHeaderColor;
       reportWrapper.Report_Id__c = selectedReportID.subString(0,15);     
       upsert reportWrapper;

     }
     return null;     
    }

    public void cancel(){
      editStyle = false;
    }

  public PageReference sendEmail(){

    PageReference pgRef = Page.ContactTestPage;    
    pgRef.getParameters().put('reportId', selectedReportID);
    pgRef.setRedirect(true);
    Blob pdfval = pgRef.getContentAsPdf();

    Messaging.EmailFileAttachment attch = new Messaging.EmailFileAttachment();
    attch.setBody(pdfval);
    attch.setFileName('ReportPdf.pdf');
    // Send an email to the Apex job's submitter notifying of job completion.
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    List<String> emailAddresses = getEmailAddresses();

    mail.setToAddresses(emailAddresses);
    mail.setSubject('Report Results');
    mail.setPlainTextBody('Report Pdf');
    mail.setSaveAsActivity(false);
    mail.setFileAttachments(new List<Messaging.EmailFileAttachment>{attch});

    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    saveData();
    return null;
  }

  public List<String> getEmailAddresses(){

    List<String> emailAddresses = new List<String>();
    if(reportWrapper.Id != null){
      for(Contact con : [SELECT Email FROM Contact WHERE Id = :reportWrapper.Id]){
        if(con.Email != null){
          emailAddresses.add(con.Email);
        }
      }
    }
    if(reportWrapper.Id != null){
      for(Lead ld : [SELECT Email FROM Lead WHERE Id = :reportWrapper.Id]){
        if(ld.Email != null){
          emailAddresses.add(ld.Email);
        }
      }
    }
    if(reportWrapper.Id != null){
      for(User usr : [SELECT Email FROM User WHERE Id = :reportWrapper.Id]){
        if(usr.Email != null){
          emailAddresses.add(usr.Email);
        }
      }
    }
    if(!String.IsBlank(additionalEmails)){
      for(String str : additionalEmails.split(',')){
        emailAddresses.add(str.trim());        
      }
    }
    return emailAddresses;
  }
}

My current test class looks like:

@isTest
public class TestReportParser{ 

    public TestReportParser(){ } 

    public static testMethod void MyTestReportParser(){ 
        string jsonString = '{"currency" : "ABC"}';
         List<String> mytestData; 
        ReportParser rpt = new ReportParser(); 
        ReportParser rp = new ReportParser(jsonString); 
        String mydata = rp.getHtmlTable(); 
        mytestData = rp.getHeader(); 
    }
}
2
  • What are the difficulties you have? What you have tried so far?
    – highfive
    Commented May 21, 2014 at 6:59
  • let me show you my test class @isTest public class TestReportParser{ public TestReportParser(){ } public static testMethod void MyTestReportParser(){ string jsonString = '{"currency" : "ABC"}'; List<String> mytestData; ReportParser rpt = new ReportParser(); ReportParser rp = new ReportParser(jsonString); String mydata = rp.getHtmlTable(); mytestData = rp.getHeader(); } } this my test class. i am new in salesforce so not get more idea Commented May 21, 2014 at 9:54

2 Answers 2

1

First read some documentations and try to get a help from them. Below links will help to getting started.

  1. https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods
  2. https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_test.htm

You can set the page reference to your visualforce page from the test class(with the URL parameters as well). Add below code into your test class with relevant updates according to your data.

// Id reportId = 'some report Id';
// Set current page *to Your_VFPage* page and initializing data
   Pagereference ref = Page.*Your_Page*;
   Test.setCurrentPageReference(ref);
   System.currentPageReference().getParameters().put('reportId', reportId);   //  jobSchedule Id parameter for SampleLocationsForSampleCollection VF page

Also if you need to call the controller methods directly simply create an instance of the controller and call the methods to test them.

CustomizedReportController controller = new CustomizedReportController();
controller.initDefaultTheme();
...

But make sure you are handling null occurrences correctly, if not your code will break and your test class will fail.

7
  • I have tried this thing in my code I got 58% coverage but one error i still getting is "Methods defined as TestMethod do not support getContent call, test skipped" in my "sendEmail();" method. can please help me to solve this error. Commented May 22, 2014 at 5:53
  • Before doing a webservice callout, check whether the it's running from a test execution. Check this link salesforce.stackexchange.com/questions/12344/…
    – highfive
    Commented May 22, 2014 at 5:59
  • i am getting this error when call "ref =controller.sendEmail()" method but this method is not webservice callout method this is normal method and not get any other webservice callout in debug log file. Commented May 22, 2014 at 6:57
  • Hey but inside the sendEmail() you are sending the mail(obvious) by calling ` Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });. Wrap that code line with if (!System.Test.isRunningTest()){}` and give a try. Also make sure to do the same for any of other callouts to make sure they will not affect your test class.
    – highfive
    Commented May 22, 2014 at 7:21
  • hi thanks for reply i have warped code like this Messaging.EmailFileAttachment attch; if(!System.Test.isRunningTest()){ attch = new Messaging.EmailFileAttachment(); } but still facing same issue. Commented May 22, 2014 at 7:58
0

Can you please use the below test case and try it ?

@isTest
public class CustomizedReportControllerTest{ 
    static testMethod void TestCustomizedReportController(){    

        contact c = new contact();
        c.lastname = 'testCon';
        c.email = '[email protected]';
        insert c;

        ApexPages.currentPage().getParameters().put('reportId', c.id);

        CustomizedReportController c = new CustomizedReportController();
        c.saveData();
        c.sendEmail();
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .