+ Start a Discussion
cambart14cambart14 

Code Coverage on Apex Class used as Visualforce Page Controller

I have a custom Visualforce page that is used to create an interactive report for our sales teams.  Once a sales rep clicks on custom tab, it brings them to the Visualforce page, which in turn calls the Apex class.  The Apex class queries the rep's opportunities and puts them into a list.  The Visualforce page uses that list and some CSS and Javascript to render an interactive report for the rep.

My question is how would I get code coverage for the Apex class as it is not triggered by a record and does not have a DML statement?  It simply calls a list of records in a list and displays it to the user.
pconpcon
You can generate the data and then pass it through via your test.  For example

NoDMLClass.cls
public class NoDMLClass {
    public String doSomething(List<Account> accts) {
        // do something

        return 'I did something';
    }
}

NoDMLClass_Test.cls
@isTest
private class NoDMLClass_Test {
    static testMethod void doSomething_test() {
        List<Account> accountList = new List<Account> {
            new Account(...),
            new Account(...)
        }

        insert accountList;

        Test.startTest();

        String result = NoDMLClass.doSomething(accountList);

        Test.stopTest();

        System.assertEquals(
            'I did something',
            result,
            'Did not get the right result back'
        );
    }
}

Is this the type of thing you're talking about?
cambart14cambart14
@pcon, below is my specific Visualforce page and Apex controller class.

Visualforce Page with 'pivot' as page controller
<apex:page controller="pivot" standardStylesheets="false" sidebar="false" showHeader="true">
 <html>
    <head>
        <title>Pivot Dynamic  in Visualforce</title>
      
        <apex:stylesheet value="{!$Resource.Pivot}"/>
        <script type="text/javascript" src="{!$Resource.jquery183min}" ></script>
        <script type="text/javascript" src="{!$Resource.jqueryui192custommin}" ></script>
        <script type="text/javascript" src="{!$Resource.PivotJS}" ></script>
        <script type="text/javascript" src="{!$Resource.jsapi}" ></script>
        <script type="text/javascript" src="{!$Resource.gchartrenderers}" ></script>

    </head>
    <style>
        
    </style>
    <body>
        <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart", "charteditor"]});
        var derivers =     $.pivotUtilities.derivers;
        var renderers =    $.extend($.pivotUtilities.renderers, $.pivotUtilities.gchart_renderers);
        var tpl =          $.pivotUtilities.aggregatorTemplates;
       
        var InputData={!Data};
            $(function(){
                        $("#output1").pivotUI(
                        InputData,
                        {aggregators: {
                            "Sum Of Expected Revenue": function() { return tpl.sum()(["ExpectedTotalPrice"])},
                            "Sum Of Quantity": function() { return tpl.sum()(["Quantity"])},
                            "Count":      function() { return tpl.count()() },
                        },
                        rows: ["RevenueQuarter","AccountName","OpportunityName","Probability","ItemNumber","CurrencyCode"]
                        }
             );
             });
        </script>  
        <div id="output1" style="margin: 10 px;"></div>
    </body>
</html>
</apex:page>

Apex controller class
Public with sharing class pivot
{
    public string pivotContent{get;set;}
    public string ReturnValue{get;set;}
    public string getPivot{get;set;}

  public string getData()
  {    List<PivotData> PivotDataList=new List<PivotData>();
  
   List<OpportunityLineItem> OppList=[Select Opportunity.Account.Name,Opportunity.StageName,Product_Date__c, Opportunity.Account.ShippingCity,
   Opportunity.Amount,Opportunity.RecordTypeID,convertcurrency(Expected_Total_Price__c),Opportunity.IsClosed, Quantity, ID, Opportunity.Type, Product2.Amended_Product_Family__c,
   Revenue_Quarter__c, Opportunity.Close_Quarter__c, TotalPrice,Opportunity.Account.ShippingCountry,Opportunity.Account.ShippingState,Opportunity.Opportunity_Number__c,
   Opportunity.Name,PriceBookEntry.Product2.Name,Opportunity.Probability,PriceBookEntry.Product2.Description FROM OpportunityLineItem 
   WHERE Opportunity.OwnerID =: UserInfo.getUserId() AND Opportunity.IsClosed = FALSE ];
   
       for(OpportunityLineItem o :OppList)
       {
           PivotData p=new PivotData();
           p.AccountName=o.Opportunity.Account.Name;
           p.StageName=o.Opportunity.StageName;
           p.CalendarYear=string.valueof(o.Product_Date__c.Year());
           p.CalendarMonth=string.valueof(o.Product_Date__c.Month());
           p.RevenueQuarter=o.Revenue_Quarter__c;
           p.CloseQuarter=o.Opportunity.Close_Quarter__c;
           p.ExpectedTotalPrice=o.Expected_Total_Price__c;
           p.OpportunityName=o.Opportunity.Name;
           p.ItemNumber=o.PriceBookEntry.Product2.Name;
           p.Probability=o.Opportunity.Probability;
           p.ItemDescription=o.PriceBookEntry.Product2.Description;
           p.Quantity=o.Quantity;
           p.Type=o.Opportunity.Type;
           p.TotalPrice=o.TotalPrice;
           p.ShippingCity=o.Opportunity.Account.ShippingCity;
           p.ShippingCountry=o.Opportunity.Account.ShippingCountry;
           p.ShippingState=o.Opportunity.Account.ShippingState;
           p.OpportunityNumber=o.Opportunity.Opportunity_Number__c;
           p.AmendedProductFamily=o.Product2.Amended_Product_Family__c;
           PivotDataList.add(p);
       }
       
       List<SObject> objects = new List<SObject>();  
       
       getPivot='visibility: visible';
       return JSON.serialize(PivotDataList);
  }
   public void Result()  
      {  
          getPivot='visibility: hidden';
          ReturnValue = 'Save successfully  '; 
      } 

  public class PivotData
  {
     public string AccountName{get;set;}
     public string StageName{get;set;}
     public string CalendarYear{get;set;}
     public string CalendarMonth{get;set;}
     public decimal ExpectedTotalPrice{get;set;}
     public string OpportunityName{get;set;}
     public string ItemNumber{get;set;}
     public decimal Probability{get;set;}
     public string ItemDescription{get;set;}
     public decimal Quantity{get;set;}
     public string Type{get;set;}
     public string ShippingCity{get;set;}
     public string RevenueQuarter{get;set;}
     public string CloseQuarter{get;set;}
     public decimal TotalPrice{get;set;}
     public string ShippingCountry{get;set;}
     public string ShippingState{get;set;}
     public string OpportunityNumber{get;set;}
     public string AmendedProductFamily{get;set;}
         
  }

}


 
pconpcon
So for your code, you'll want to insert a bunch of OpportunityLineItem records (and their required parents) that meet your where criteria.  Then inside your startTest/stopTest call your getData method and your Result method.
 
static testMethod pivotTest() {
    // Code to insert accounts, opportunities, opportunity line items, etc

    Test.startTest();

    Pivot p = new Pivot();

    String result = p.getData();

    System.assertEquals(
        'visibility: visible',
        pivot.getPivot,
        'Did not get the right pivot css'
    );

    p.result();

    System.assertEquals(
        'visibility: hidden',
        pivot.getPivot,
        'Did not get the right pivot css'
    );
    System.assertEquals(
        'Save successfully  ',
        pivot.returnValue,
        'Did not get the right return value'
    );

    Test.stopTest();

    List<Pivot.PiviotData> pivotData;

    // Code to deserialize result JSON into pivotData
    // Code to make sure the PivotData was set right
}
yosra saidaniyosra saidani
@cambart14
I need to develop Pivot Table in salesforce
can you please share your Js Ressource ? 
Thank you
 
cambart14cambart14
@yosra saidani

The resources referenced in this come from  nicolaskruchten's Pivot Table project: https://github.com/nicolaskruchten/pivottable.