• Adaniels117
  • NEWBIE
  • 20 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 6
    Replies
Hey SF Forums,

I created a controller that powers a visualforce page and i'm struggling with my test class to get enough code coverage. I've created 2 test classes that only have achieved 16% and 7% coverage and wanted to know if anyone had suggestions as to how i can improve upon it.



Here's the VF Page: "PivotPageCaseOwnerlastweek"
<apex:page controller="pivotsupportcaselastweek" showHeader="FALSE">
    <head>
        <title>Cases Last Week by Owner</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>
    </head>
    
    <style>
        * {font-family: Verdana;}
    </style>
    <script type="text/javascript">
       function savedata()
       {
          var pivotContent=document.getElementById("output").innerHTML;
          TestAF(pivotContent);
         return true;
       }
 </script>
      <apex:form >
      <div style="overflow: scroll; width: 100%; height: 100%;">
      <span class="btn" onclick="return savedata()"   > Get Pivot Data</span> 
      
   
     <apex:actionfunction action="{!Result}" name="TestAF" rerender="resultPanel" status="TestStatus">
   
   
     <apex:param assignto="{!pivotContent}" name="FirstParameter" value=""> </apex:param>
    </apex:actionfunction>
    <apex:outputpanel id="resultPanel">
    <apex:actionstatus id="TestStatus" starttext="Processing..." stoptext="">
     <b></b>
     </apex:actionstatus>
   
        <script type="text/javascript">
        var InputData={!Data};
            $(function(){
                        $("#output").pivot(
                        InputData
           ,
        {
            rows: ["Owner"],
            cols: ["Day"]
        }
    );
             });
        </script>

     
        <div id="output" style="margin: 10px;"></div>
</apex:outputpanel>
   </div> </apex:form>

</apex:page>
This is the Class:
Public with sharing class pivotsupportcaselastweek
{
    public string pivotContent{get;set;}
    public string ReturnValue{get;set;}
    public string getPivot{get;set;}
    public boolean exportPdf{get;set;}

  public string getData()
  {    List<PivotData> PivotDataList=new List<PivotData>();
       List<Case> CaseList=[Select Account.Name,Owner.Name,Case_Owner_Role__c,Issue__c,Status,Day_Closed__c,Closed_Date__c,ClosedDate,CreatedDate,Type,Reason,Vendor_ID__c,Are_you_a__c, Where__c from case where ClosedDate = LAST_WEEK AND Case_Owner_Role__c='Support Rep' ORDER BY ClosedDate DESC ];
       for(Case o :CaseList)
       {
           PivotData p=new PivotData();
           p.AccountName=o.Account.Name;
           p.Status=o.Status;
           p.ClosedDay=o.Closed_Date__c;
           p.OpenYear=string.valueof(o.CreatedDate.Year());
           p.OpenMonth=string.valueof(o.CreatedDate.month());
           p.Type=o.Type;
           p.Issue=o.Issue__c;
           p.CaseReason=o.Reason;
           p.VendorID=o.Vendor_ID__c;
           p.Day=o.Day_Closed__c;
           p.AreYouA=o.Are_you_a__c;
           p.Case_Where=o.Where__c;
           p.ClosedYear=string.valueof(o.ClosedDate.Year());
           p.ClosedMonth=string.valueof(o.ClosedDate.month());
           p.Owner=o.Owner.Name;
           p.OwnerRole=o.Case_Owner_Role__c;
           
           PivotDataList.add(p);
           
       }
       getPivot='visibility: visible';
       exportPdf=false;
       return JSON.serialize(PivotDataList);
  }
   public void Result()  
      {  
          getPivot='visibility: hidden';
         exportPdf=true;
             ReturnValue = 'Save successfully  '; 
      } 
   Public PageReference ViewPdf()
   {
        PageReference pageRef= new PageReference('/apex/ViewPivot');
          pageRef.setredirect(false);       
          return pageRef;
   }


  public class PivotData
  {
     public string AccountName{get;set;}
     public string Status{get;set;}
     public string Owner{get;set;}
     public string Type{get;set;}
     public string CaseReason{get;set;}
     public string AreYouA{get;set;}
     public string Day{get;set;}
     public string VendorID{get;set;}
     public string Issue{get;set;}
     public string Case_Where{get;set;}
     public date ClosedDay{get;set;}
     public string OpenYear{get;set;}
     public string OpenMonth{get;set;}
     public string ClosedYear{get;set;}
     public string ClosedMonth{get;set;}
     public string OwnerRole{get;set;}
  }
}
And my two test classes. This first one achieves 16%:
 
@isTest
public class PivotTestClassv2 {
static testMethod void PivotPageCaseOwnerlastweek_Test()
{
//Test converage for the myPage visualforce page
PageReference pageRef = Page.PivotPageCaseOwnerlastweek;
Test.setCurrentPageReference(pageRef);
Account newAccount = new Account (name='XYZ Organization');
insert newAccount;
//create first ccase
Case myCase = new Case (Are_you_a__c='Other',
Reason='Other',
Where__c='Other',
Status='Closed',
Issue__c='Other',
AccountId=newAccount.id);
insert myCase;


// create an instance of the controller
pivotsupportcaselastweek myPageCon = new pivotsupportcaselastweek();
//try calling methods/properties of the controller in all possible scenarios
// to get the best coverage.
string Type = myPageCon.GetData();



}
}
And this one gets 7% coverage:
@isTest
private class MyPivotTest3 {
public static testMethod void pivotsupportcaselastweek() {
       
       //Use the PageReference Apex class to instantiate a page
       PageReference pageRef = Page.PivotPageCaseOwnerlastweek;
       
       //In this case, the Visualforce page named 'PivotPageCaseOwnerlastweek;' is the starting point of this test method. 
       Test.setCurrentPage(pageRef);
     
       //Instantiate and construct the controller class.   
       pivotsupportcaselastweek controller = new pivotsupportcaselastweek();

       //Example of calling an Action method. Same as calling any other Apex method. 
       //Normally this is executed by a user clicking a button or a link from the Visualforce
       //page, but in the test method, just test the action method the same as any 
       //other method by calling it directly. 

       //The .getURL will return the page url the Save() method returns.
       String nextPage = controller.ViewPdf().getUrl();

       //Check that the save() method returns the proper URL.
       System.assertEquals('/apex/ViewPivot', nextPage);

       //Add parameters to page URL
       ApexPages.currentPage().getParameters().put('qp', 'yyyy');
     
       //Instantiate a new controller with all parameters in the page
       controller = new pivotsupportcaselastweek(); 

       

       //Verify that the success page displays
       System.assertEquals('/apex/ViewPivot', nextPage);
       
   }
   }




Does anyone have any ideas as to how I can bulk up the coverage....and maybe consolidate the test classes into one? Any advice would be greatly appreciated!

 
Hey Everyone,

Beginner here, hoping if somebody could help me with my trigger. I'm attempting to create a new contract when a custom object is updated.

It allows me to save the trigger, but when i update the custom object I'm getting the following error:

Apex trigger AutoContract caused an unexpected exception, contact your administrator: AutoContract: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.AutoContract: line 11, column 1

Here is the code i'm using:

/////////////////////////////////////////////////

trigger AutoContract on Zuora__SubscriptionProductCharge__c (After Update) {
List<Contract> listContracts= new List<Contract>();
for(Zuora__SubscriptionProductCharge__c S: Trigger.new){
Contract C= new Contract();
C.Description=S.Zuora__ProductDescription__c;
C.accountid=S.Zuora__Account__r.Id;
C.Type_of_Sale__c=S.Zuora__ProductName__c;
C.Payment_Plan__c=S.Zuora__BillingPeriod__c;
C.Contract_Total__c=S.Zuora__ExtendedAmount__c;
C.StartDate=S.Zuora__EffectiveStartDate__c;
C.Account.Name=S.Zuora__Account__r.Name;
C.User__c='00550000002TLtx';
listContracts.add(c);
}

   if(listContracts.isEmpty()== false)
{Database.insert(listContracts);

}


  }

//////////////////////////////////////////////////

It seems that the line that is causing the error is the line where i'm trying to map the Contract account name. Can anybody help explain why i'm getting the error and what I need to add to fix?

Thank you!

Hey guys, I'm having trouble writing a test class for this trigger. Its my first trigger, works in Sandbox...just not sure where to start with creating a test class so I can successfully deploy in production. Any Guidance would be incredibly helpful:

 

trigger HasSoldTask on Task(after update, after insert)
{
List<Id> accIds = new List<Id>();
   for(Task t : Trigger.new)
    {
        If (t.status=='sold')
        {
            accids.add(t.accountid);
        }
    }
   Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id, Has_Sold_Opp__c FROM Account WHERE Id IN :accIds]);
    
    Map<Id, Account> updateMap = new Map<Id, Account>();
    
    for (Task t: Trigger.new)
    {
        If (t.Accountid <> null && (t.Status == 'sold') && (accMap.get(t.AccountId).Has_Sold_Opp__c < t.LastModifiedDate || accMap.get(t.AccountId).Has_Sold_Opp__c ==null))
        {
            Account acc = accMap.get(t.AccountId);
            acc.Has_Sold_Opp__c  = t.LastModifiedDate;
            updateMap.put(t.AccountId, acc);
        }
    }
    update updateMap.values();
    }

 What should I be testing for? Where do I start?

Hey guys, long time listener...first time caller.

 

Just beginning at Apex, need some help writing this trigger. I want a custom date field to update on the Account level whenever a Task within the Account is updated to Status=Sold.

 

The error i'm getting is "Compile Error: expecting a semi-colon, found 'Account' at line 8 column 6"

 

trigger HasSoldTask on Task (after insert) {
for (Task t: Trigger.new){
    if (t.accountID != NULL){
      acctIDs.add(t.accountID);
//Create a map to match the task related to ID's with their corresponding account ID's
      Map<ID, Account> acctMap = new Map<ID, Account> ([Select ID, Has_Sold_Opp__c from Account where ID in :acctIDs])
//Create the account object
      Account acctRec = acctMap.get(t.accountID);

//If the account ID isn't null, the subject line starts with "sw", and the task has been marked as completed
//Check to see if the Last_SW_Activity__c field is current compared with the latest completed activity    
    If ((t.Status == 'Sold') && (acctMap.get(t.accountID).Has_Sold_Opp__c < t.LastModifiedDate || acctMap.get(t.accountID).Has_Sold_Opp__c ==null)){
//Update the Last_SW_Activity__c field on the account object with the task's end date  
          acctrec.Has_Sold_Opp__c  = t.LastModifiedDate;
   
      }
  }
  update acctRec;
  }

 If I add a semi colon before " Account acctRec = acctMap.get(t.accountID);" Then I get "Compile Error: Variable does not exist: acctIDs at line 6 column 110"

 

Any ideas? Thanks!

Hey SF Forums,

I created a controller that powers a visualforce page and i'm struggling with my test class to get enough code coverage. I've created 2 test classes that only have achieved 16% and 7% coverage and wanted to know if anyone had suggestions as to how i can improve upon it.



Here's the VF Page: "PivotPageCaseOwnerlastweek"
<apex:page controller="pivotsupportcaselastweek" showHeader="FALSE">
    <head>
        <title>Cases Last Week by Owner</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>
    </head>
    
    <style>
        * {font-family: Verdana;}
    </style>
    <script type="text/javascript">
       function savedata()
       {
          var pivotContent=document.getElementById("output").innerHTML;
          TestAF(pivotContent);
         return true;
       }
 </script>
      <apex:form >
      <div style="overflow: scroll; width: 100%; height: 100%;">
      <span class="btn" onclick="return savedata()"   > Get Pivot Data</span> 
      
   
     <apex:actionfunction action="{!Result}" name="TestAF" rerender="resultPanel" status="TestStatus">
   
   
     <apex:param assignto="{!pivotContent}" name="FirstParameter" value=""> </apex:param>
    </apex:actionfunction>
    <apex:outputpanel id="resultPanel">
    <apex:actionstatus id="TestStatus" starttext="Processing..." stoptext="">
     <b></b>
     </apex:actionstatus>
   
        <script type="text/javascript">
        var InputData={!Data};
            $(function(){
                        $("#output").pivot(
                        InputData
           ,
        {
            rows: ["Owner"],
            cols: ["Day"]
        }
    );
             });
        </script>

     
        <div id="output" style="margin: 10px;"></div>
</apex:outputpanel>
   </div> </apex:form>

</apex:page>
This is the Class:
Public with sharing class pivotsupportcaselastweek
{
    public string pivotContent{get;set;}
    public string ReturnValue{get;set;}
    public string getPivot{get;set;}
    public boolean exportPdf{get;set;}

  public string getData()
  {    List<PivotData> PivotDataList=new List<PivotData>();
       List<Case> CaseList=[Select Account.Name,Owner.Name,Case_Owner_Role__c,Issue__c,Status,Day_Closed__c,Closed_Date__c,ClosedDate,CreatedDate,Type,Reason,Vendor_ID__c,Are_you_a__c, Where__c from case where ClosedDate = LAST_WEEK AND Case_Owner_Role__c='Support Rep' ORDER BY ClosedDate DESC ];
       for(Case o :CaseList)
       {
           PivotData p=new PivotData();
           p.AccountName=o.Account.Name;
           p.Status=o.Status;
           p.ClosedDay=o.Closed_Date__c;
           p.OpenYear=string.valueof(o.CreatedDate.Year());
           p.OpenMonth=string.valueof(o.CreatedDate.month());
           p.Type=o.Type;
           p.Issue=o.Issue__c;
           p.CaseReason=o.Reason;
           p.VendorID=o.Vendor_ID__c;
           p.Day=o.Day_Closed__c;
           p.AreYouA=o.Are_you_a__c;
           p.Case_Where=o.Where__c;
           p.ClosedYear=string.valueof(o.ClosedDate.Year());
           p.ClosedMonth=string.valueof(o.ClosedDate.month());
           p.Owner=o.Owner.Name;
           p.OwnerRole=o.Case_Owner_Role__c;
           
           PivotDataList.add(p);
           
       }
       getPivot='visibility: visible';
       exportPdf=false;
       return JSON.serialize(PivotDataList);
  }
   public void Result()  
      {  
          getPivot='visibility: hidden';
         exportPdf=true;
             ReturnValue = 'Save successfully  '; 
      } 
   Public PageReference ViewPdf()
   {
        PageReference pageRef= new PageReference('/apex/ViewPivot');
          pageRef.setredirect(false);       
          return pageRef;
   }


  public class PivotData
  {
     public string AccountName{get;set;}
     public string Status{get;set;}
     public string Owner{get;set;}
     public string Type{get;set;}
     public string CaseReason{get;set;}
     public string AreYouA{get;set;}
     public string Day{get;set;}
     public string VendorID{get;set;}
     public string Issue{get;set;}
     public string Case_Where{get;set;}
     public date ClosedDay{get;set;}
     public string OpenYear{get;set;}
     public string OpenMonth{get;set;}
     public string ClosedYear{get;set;}
     public string ClosedMonth{get;set;}
     public string OwnerRole{get;set;}
  }
}
And my two test classes. This first one achieves 16%:
 
@isTest
public class PivotTestClassv2 {
static testMethod void PivotPageCaseOwnerlastweek_Test()
{
//Test converage for the myPage visualforce page
PageReference pageRef = Page.PivotPageCaseOwnerlastweek;
Test.setCurrentPageReference(pageRef);
Account newAccount = new Account (name='XYZ Organization');
insert newAccount;
//create first ccase
Case myCase = new Case (Are_you_a__c='Other',
Reason='Other',
Where__c='Other',
Status='Closed',
Issue__c='Other',
AccountId=newAccount.id);
insert myCase;


// create an instance of the controller
pivotsupportcaselastweek myPageCon = new pivotsupportcaselastweek();
//try calling methods/properties of the controller in all possible scenarios
// to get the best coverage.
string Type = myPageCon.GetData();



}
}
And this one gets 7% coverage:
@isTest
private class MyPivotTest3 {
public static testMethod void pivotsupportcaselastweek() {
       
       //Use the PageReference Apex class to instantiate a page
       PageReference pageRef = Page.PivotPageCaseOwnerlastweek;
       
       //In this case, the Visualforce page named 'PivotPageCaseOwnerlastweek;' is the starting point of this test method. 
       Test.setCurrentPage(pageRef);
     
       //Instantiate and construct the controller class.   
       pivotsupportcaselastweek controller = new pivotsupportcaselastweek();

       //Example of calling an Action method. Same as calling any other Apex method. 
       //Normally this is executed by a user clicking a button or a link from the Visualforce
       //page, but in the test method, just test the action method the same as any 
       //other method by calling it directly. 

       //The .getURL will return the page url the Save() method returns.
       String nextPage = controller.ViewPdf().getUrl();

       //Check that the save() method returns the proper URL.
       System.assertEquals('/apex/ViewPivot', nextPage);

       //Add parameters to page URL
       ApexPages.currentPage().getParameters().put('qp', 'yyyy');
     
       //Instantiate a new controller with all parameters in the page
       controller = new pivotsupportcaselastweek(); 

       

       //Verify that the success page displays
       System.assertEquals('/apex/ViewPivot', nextPage);
       
   }
   }




Does anyone have any ideas as to how I can bulk up the coverage....and maybe consolidate the test classes into one? Any advice would be greatly appreciated!

 
Hey Everyone,

Beginner here, hoping if somebody could help me with my trigger. I'm attempting to create a new contract when a custom object is updated.

It allows me to save the trigger, but when i update the custom object I'm getting the following error:

Apex trigger AutoContract caused an unexpected exception, contact your administrator: AutoContract: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.AutoContract: line 11, column 1

Here is the code i'm using:

/////////////////////////////////////////////////

trigger AutoContract on Zuora__SubscriptionProductCharge__c (After Update) {
List<Contract> listContracts= new List<Contract>();
for(Zuora__SubscriptionProductCharge__c S: Trigger.new){
Contract C= new Contract();
C.Description=S.Zuora__ProductDescription__c;
C.accountid=S.Zuora__Account__r.Id;
C.Type_of_Sale__c=S.Zuora__ProductName__c;
C.Payment_Plan__c=S.Zuora__BillingPeriod__c;
C.Contract_Total__c=S.Zuora__ExtendedAmount__c;
C.StartDate=S.Zuora__EffectiveStartDate__c;
C.Account.Name=S.Zuora__Account__r.Name;
C.User__c='00550000002TLtx';
listContracts.add(c);
}

   if(listContracts.isEmpty()== false)
{Database.insert(listContracts);

}


  }

//////////////////////////////////////////////////

It seems that the line that is causing the error is the line where i'm trying to map the Contract account name. Can anybody help explain why i'm getting the error and what I need to add to fix?

Thank you!

Hey guys, long time listener...first time caller.

 

Just beginning at Apex, need some help writing this trigger. I want a custom date field to update on the Account level whenever a Task within the Account is updated to Status=Sold.

 

The error i'm getting is "Compile Error: expecting a semi-colon, found 'Account' at line 8 column 6"

 

trigger HasSoldTask on Task (after insert) {
for (Task t: Trigger.new){
    if (t.accountID != NULL){
      acctIDs.add(t.accountID);
//Create a map to match the task related to ID's with their corresponding account ID's
      Map<ID, Account> acctMap = new Map<ID, Account> ([Select ID, Has_Sold_Opp__c from Account where ID in :acctIDs])
//Create the account object
      Account acctRec = acctMap.get(t.accountID);

//If the account ID isn't null, the subject line starts with "sw", and the task has been marked as completed
//Check to see if the Last_SW_Activity__c field is current compared with the latest completed activity    
    If ((t.Status == 'Sold') && (acctMap.get(t.accountID).Has_Sold_Opp__c < t.LastModifiedDate || acctMap.get(t.accountID).Has_Sold_Opp__c ==null)){
//Update the Last_SW_Activity__c field on the account object with the task's end date  
          acctrec.Has_Sold_Opp__c  = t.LastModifiedDate;
   
      }
  }
  update acctRec;
  }

 If I add a semi colon before " Account acctRec = acctMap.get(t.accountID);" Then I get "Compile Error: Variable does not exist: acctIDs at line 6 column 110"

 

Any ideas? Thanks!