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
Thakkar ParthThakkar Parth 

Help creating test class

I'm new to using APEX and would really appreciate your help. I found this bit of code online  I need to write a test class to ensure it has coverage for deployment. Can someone please help me construct a test class, or point me in the right direction?  It describes charts with a combination of Bar and Line charts and with pie chart in one grid.

Thanks, Marc

=== Class ====

public class HighchartsController
{ 
     public String str {
     get {
            String res = '';
            Integer i;
            //SOQL
            res = '[';
            for(i=1;i<13;i++)
            res +=  '' + (i+1) +  ',';
            res += 12;
            res += ']';
            return  res;
            }
        }
    public String bar {
     get {
            String str = '';
            Integer i;
            //SOQL
            str = '[';
            for(i=1;i<13;i++)
            str +=  '' + i + ',';
            str += 12;
            str += ']';
            return  str;
            }
    
        }
      
    public List<Integer> X
   {
    get
    {
       //X= '10';
       X=new List<Integer>();
       String q = 'Select count(Id),StageName from opportunity where StageName IN(\'Closed Won\',\'Closed Lost\') group by StageName';
      AggregateResult[] agr =Database.query(q);
     // X = '\''+ String.valueof(agr[0].get('expr0')) + ',' +String.valueof(agr[1].get('expr0')) + '\'';
      X.add(Integer.valueof(agr[0].get('expr0')));
      X.add(Integer.valueof(agr[1].get('expr0')));
      return X;
    }
   set
   {}
    }
   }

 ==== Page ====


<apex:page controller="HighchartsController">

     <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
     <script src="https://code.highcharts.com/highcharts.js"></script>
     <script src="https://code.highcharts.com/modules/exporting.js"></script>

     <div id="container" style="min-width: 310px; height: 400px; margin:0 auto"></div>

        <script>
            pieOrdinate = {!X};
           // pieOrdinate = ServerStr.split(',');
             $(function () {
             $('#container').highcharts({
             title: {
             text: 'Chart showing opportunities'
        },
        xAxis:{
                categories: ['Jan','Feb','Mar','Apr','May','Jun','July','Aug','Sept','Oct','Nov','Dec']
            },
              labels: {
              items: [{
              html: 'Opportunities',
              style: {
                    left: '50px',
                    top: '18px',
                    color: (Highcharts.theme && Highcharts.theme.textColor) || 'black'
                }
            }]
        },
        series: [ {
            type: 'column',
            name: 'Indian Railways',
            data: {!str}
            //data:[2,3,4,5,6]
        },
         {
            type: 'spline',
            name: 'Monthly Sales', // Average
           // data: [3, 2.67, 3, 6.33, 3.33],   
           data :{!bar},
            marker: {
                lineWidth: 2,
                lineColor: Highcharts.getOptions().colors[3],
                fillColor: 'white'
            }
        },
        {
            type: 'pie',
            name: 'Total consumption',
            data: [ {
                name: 'Lost',
                //y:23,
                y :parseInt(pieOrdinate[0]),
                sliced:true,
                selected:true,
                color: Highcharts.getOptions().colors[1] // Opp's Lost color
              }, 
               {
                name: 'Won',
                y:parseInt(pieOrdinate[1]),
                color: Highcharts.getOptions().colors[2] // Opp's won color
              }],
               center: [100, 80],
               size: 100,
               showInLegend: false,
               dataLabels:
               {
                 enabled:true
               }
        }]
    });
});
  </script>
</apex:page>



James LoghryJames Loghry
You'll want to create a separate Apex class that constructs your controller and calls all your methods.  For an idea of how this works, please read the documentation here first: https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

Y
our class may look something like the following:

@isTest
private class HighchartsControllerTest{
    static testmethod void testStrGetter(){
        //construct HighchartsController
        //Call ctrl.str;
        //System.assert that str is as expected.
    }

    static testmethod void testBarGetter(){
        //construct controller
        //call ctrl.bar;
        //System.assert that bar is as expected.
    }

    static testmethod void testXWithValidOpportunities(){
        //Create "mock" aka fake Opportunity records.  
        //construct controller
        //call ctrl.X
        //System.assert that X is as expected.
    }

    static testmethod void testXWithNoOpportunities(){
        //construct controller
        //call ctrl.X
        //System.assert that X is as expected.
    }
}

Note, that I prototyped you two method for testing "X".  A good unit test will test all the conditions.  Positive, Negative, boundary conditions, et al. 

To run the unit test to verify everything is working smoothly, you can open up Developer Console (Setup->Developer Console) and run the unit test there.

Thakkar ParthThakkar Parth
Thanks James for the quick response  and helping in a prototype for the Test class . Can you please help me to give an example for the method just for the sample...Like one method as above please .

static testmethod void testStrGetter(){
        //construct HighchartsController
        //Call ctrl.str;
        //System.assert that str is as expected.
    }
James LoghryJames Loghry
static testmethod void testXWithValidOpportunities(){
    //Creating mock objects
    //There are likely additional fields you will need to add to each Opportunity below.
    List<Opportunity> opps = new List<Opportunity>();
    opps.add(new Opportunity(Name='MyOpp',StageName='Closed Won');
    opps.add(new Opportunity(Name='MyOpp2',StageName='Closed Lost');
    opps.add(new Opportunity(Name='MyOpp3',StageName='Open');
    insert opps;

    //Call Test.startTest to ensure asynchronous calls finish before your System.assert calls
    Test.startTest();
    //Constructing your controller
    HighchartsController ctrl = new HighchartsController();
    //Call your X getter here
    Integer x = ctrl.X;
    //Call Test.stopTest to ensure any asynchronous calls finish
    Test.stopTest();

    //Assert your expectations here.. The more System.asserts the merrier.
    System.assertEquals(3,[Select Id From Opportunities].size());
    //X should be 2 since there are 2 closed opportunities
    System.assertEquals(2,x);
 }

I've written out the test class for "testXWithValidOpportunities", which is probably the most complicated test class you'll write with that controller.  That should give you a good starting point.  Note, that you may have other required fields on the Opportunity you'll need to fill in.