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
Ty WhitfieldTy Whitfield 

Write test for Apex Page w/Controller with user input

I have a VF page that has various outcomes based upon user input.  How do I create a test to deploy into production?
VFP

<apex:page sidebar="false" Controller="SplitExecutionAgentController" > 
      <apex:pageBlock > 
         <apex:form >             
             <apex:outputPanel id="resultPanel">
             <apex:actionStatus startText="requesting..."  stopText="" id="myStatus" />                
          <apex:actionFunction action="{!createNewOpps}" name="createNewOppsAF" reRender="resultPanel" status="myStatus" >
              <apex:param name="firstParam" assignTo="{!linePak}" value="" />
              <apex:param name="secondParam" assignTo="{!lineQty}" value="" />
             </apex:actionFunction>
             
               <apex:actionFunction action="{!updateOpps}" name="updateOppsAF" reRender="resultPanel" status="myStatus" >
              <apex:param name="firstParam" assignTo="{!linePak}" value="" />
              <apex:param name="secondParam" assignTo="{!lineQty}" value="" />
             </apex:actionFunction>
             <apex:pageMessages />
                  </apex:outputPanel>
              <apex:inputHidden value="{!newOpps.TotalPrice}" id="totalPrice" />
        <apex:inputHidden value="{!newOpps.PricebookEntryID}" id="priceBookEntryId" />
        <apex:inputHidden value="{!newOpps.UnitPrice}" id="unitPrice" />
        <apex:inputHidden value="{!newOpps.ListPrice}" id="listPrice" />
        <apex:inputHidden value="{!newOpps.Description}" id="description" />
        
         </apex:form>           
 
            <table >        
        <tr>
        <td>
             <img src=" https://www.advsyscon.com/en-us/CorporateSite/media/Images/salesforce/splitexecutionagent2.png"  style="width: 75px; " />
            </td>
        <td>
            <h1 style="font-size:1.5em">
                Split Execution Agent Opportunity Product Line Item
            </h1>
            </td>
        </tr>
    </table>
    <hr /> 
    
    <FORM  METHOD="post" NAME="MyForm" ID="MyForm">
                             <b>  <output size="60" style="border:0; background:none; font-weight: bold;" NAME="pointsTotal" />  <br />
                         <script> document.MyForm.pointsTotal.value = "Found {!Text(newOpps.Quantity)} Total Execution Agent Points";</script>
                       <B>Points Remaining: </B><output disabled="true" style="border:0; background:none"  NAME="VarSum" VALUE="0" SIZE="15" MAXLENGTH="5" ONCHANGE="calculate(this)" />
              </b>
                       <script>
                           
                                 if("{!closedWon}" != 'true')
                                 {
                                     alert('This opportunity must be "Closed Won" in order to use this utility');
                                     window.history.back();
                                 }
                                
                                 if("{!Text(newOpps.Quantity)}")
                                 {
                                     document.MyForm.VarSum.value = "{!Text(newOpps.Quantity)}";                                  
                                     
                                 }else{
                                     
                                     
                                     if("{!totalCount}" == 0)
                                     {
                                         alert('Unable to locate an ActiveBatch Execution Agent product line item in this opportunity.');
                                         window.history.back();
                                     }else{
                                         alert("{!totalCount}" + ' ActiveBatch Execution Agent product line items were found in this opportunity.  Unfortunately the line-item splitter only works when a single Execution Agent line item is present in the opportunity.  To remedy the problem make sure that only one \"Execution Agent\" line item is present in your opportunity.  If you feel this is a SalesForce error, please contact your SalesForce administrator.');
                                         window.history.back();
                                     }                        
                                     
                                     
                                 }                               
                                 
                                 
                                 
                                 </script>
              <hr />
        <table id="myTable">
            <tbody>
            
                <th></th>
             <th><b>Quantity</b></th>
        <th></th>
        <th><b>PakSize (Points)</b></th>        
            <tr>
                <td> <INPUT TYPE="button" style="visibility:hidden" disabled="true" NAME="id" /></td>
            <td> <INPUT TYPE="text" Id="qty0" NAME="qty0" VALUE="0" onfocus="this.value=''" ONCHANGE="calculate(this)" SIZE="15" MAXLENGTH="5"  />
                </td>
             <td  style="width:50px"></td>
            <td>
                 <INPUT TYPE="text" Id="pak0" NAME="pak0" VALUE="0" SIZE="15" MAXLENGTH="5" ONCHANGE="calculate(this)" /></td></tr>
            </tbody>
        </table>
        <input type="button" Id="addMore" name="addMore" value="Add Another Multiple" onclick="generateItem();" /> 

        <hr size="1" color="#c6c6c6" /> 
                                 <table>
                                      <tr>
         <td >      
                 <input type="button" Id="splitItems" name="splitItems" style="visibility:hidden" value="Update Opportunity" onclick="updateOpportunity();" />     
             </td>
             <td>
                 <input type="button" id="cmdCancel" onclick="window.history.go(-1); return false;"  value="Cancel" />
            </td></tr>                                     
                                 </table>                                
        
        </FORM>             
       
            </apex:pageBlock>                       

 
     <!-- Java script starts Here -->
    <script type="text/javascript">
    var counter = 0;   
        var showButtons = new Boolean(true);
    
    function calculate(which)
    {
        var runningTotal = 0;         
       
         var qty;
         var pak;
        var i = 0;
        //alert('counter = ' + counter + ' and i = ' + i);
         while(i <= counter )
            {            
                qty = parseInt(document.getElementById("myTable").rows[i + 1].cells[1].getElementsByTagName("input")[0].value);
                pak =  parseInt(document.getElementById("myTable").rows[i + 1].cells[3].getElementsByTagName("input")[0].value);                
                runningTotal = runningTotal + (qty * pak); 
                
                 if ((pak % 5) != 0){ 
                alert("All paksize point values must be divisible by 5! " + pak + " is not a valid PakSize. You must fix this error to continue."); 
                return; 
                    }
         
                i++       
                     
            }        

        var total = "{!Text(newOpps.Quantity)}";
        var remaining = total - runningTotal;
        
        if(remaining < 0){
            
             document.MyForm.VarSum.value = remaining;
            alert('You have allocated too many points. You must reallocate the point usage before continuing.');
            
            //disable buttons
              hideButtons();       
            
            
            }else{
                document.MyForm.VarSum.value = remaining;
                document.getElementById('addMore').style.visibility = 'visible';                
                 document.getElementById('splitItems').style.visibility = 'hidden';
                
                
                }
        
        if(remaining == 0){
            
              document.getElementById('addMore').style.visibility = 'hidden';                
                document.getElementById('splitItems').style.visibility = 'visible'; 
            }
     return; 
    }
        
   function hideButtons()
        {
             document.getElementById('splitItems').style.visibility = 'hidden';
             document.getElementById('addMore').style.visibility = 'hidden';
           
            }
        
        function showButtons()
        {
              document.getElementById('splitItems').style.visibility = 'visible';
             document.getElementById('addMore').style.visibility = 'visible';
            }
function goBack()
{
    window.history.go(-1); return false;
    }
function generateItem()
{
    counter++;

    var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
    
    // Insert a row in the table at the last row
	var newRow   = tableRef.insertRow(tableRef.rows.length);
    newRow.name =  counter;

	// Insert a cell in the row at index 0
	var newCell0  = newRow.insertCell(0);

	// Append a text node to the cell
     var h0 = document.createElement("button");
    h0.setAttribute('onclick', 'deleteRow(this)');
	newCell0.appendChild(h0);
    //  alert('Delete2 newRow.name = ' + newRow.name);
     var t0 = document.createTextNode("Delete Row");
    h0.appendChild(t0);
	newCell0.appendChild(h0);
    
    // Insert a cell in the row at index 0
	var newCell1  = newRow.insertCell(1);
	// Append a text node to the cell
     var h1 = document.createElement("input");
    h1.Name = 'qty'+ counter;
     h1.value = 0;
    h1.setAttribute('size', '15'); 
      h1.setAttribute('onchange', 'calculate(this)');
	newCell1.appendChild(h1);
    
     // Insert a cell in the row at index 0
	var newCell3  = newRow.insertCell(2);
	// Append a text node to the cell
    //var h3 = document.createElement("input");

       
    //newCell3.appendChild(h3);
    
   // Insert a cell in the row at index 0
	var newCell2  = newRow.insertCell(3);
	// Append a text node to the cell
     var h2 = document.createElement("input");
     h2.Name = 'pak'+ counter;
     h2.setAttribute('size', '15');
     h2.value = 0;
       h2.setAttribute('onchange', 'calculate(this)');
	newCell2.appendChild(h2);   
    
    }

 function deleteRow(el)
    {
        //  alert('invoked');
         while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
        el = el.parentNode;
        }
          el.parentNode.removeChild(el);
        counter--;
        calculate(this);
        }

function updateOpportunity()
{
         var runningTotal = 0;         
       
         var qty;
         var pak;
        var i = 0;
        //alert('counter = ' + counter + ' and i = ' + i);
         while(i <= counter )
            {            
                qty = parseInt(document.getElementById("myTable").rows[i + 1].cells[1].getElementsByTagName("input")[0].value);
                pak =  parseInt(document.getElementById("myTable").rows[i + 1].cells[3].getElementsByTagName("input")[0].value);                
                runningTotal = runningTotal + (qty * pak); 
                
                 if ((pak % 5) != 0){ 
                alert("All paksize point values must be divisible by 5! " + pak + " is not a valid PakSize. You must fix this error to continue."); 
                return; 
                    }
                
                // if i = 0 then we update the existing product line item
                // Otherwise we need to add them
                if(i ==0)
                {
                    updateOppsAF(pak, qty);
                    //alert("update existing with " + qty + " " + pak);
                }else{
                     createNewOppsAF(pak, qty);
                    //  alert("create new with "  + qty + " " + pak);
                }               
                    
         
                i++       
                     
            } 
    alert('Success');
    reDirect();
    
 
    }
     
     function reDirect()
     {
         window.location = '/' + "{!retURL}";
         }
     
    
  </script> 
</apex:page>

Controller


public  class SplitExecutionAgentController {
   @AuraEnabled
    
    public Boolean showButtons {get;set;} 
    public String closedWon {get;set;}
    Public Integer pointsTotal {get;set;} 
    Public Integer points {get;set;} 
    Public Integer pak {get;set;} 
     Public String retURL {get;set;} 
    
    Public String totalPrice {get;set;} 
    Public String PricebookEntryID {get;set;} 
    Public Integer unitPrice {get;set;} 
    Public Integer listPrice {get;set;} 
    Public String description {get;set;} 
    
    Public Integer linePak {get;set;} 
    Public Integer lineQty {get;set;} 
    
    Public Integer totalCount {get;set;} 
    Public String test {get;set;} 
   
    
     public PageReference setParams()
    {
        return null;
    }
      
  public OpportunityLineItem getNewOpps() {
      retURL = System.currentPageReference().getParameters().get('Id');
      Opportunity Opp = [SELECT stagename FROM Opportunity WHERE Id = :System.currentPageReference().getParameters().get('Id')];
      
      if(Opp.StageName == 'Closed Won')
      {
          closedWon = 'true';
      }else{
          closedWon = 'false';
      }
      totalCount= [SELECT count() FROM OpportunityLineItem WHERE PricebookEntry.Name LIKE '%Execution Agent%' AND OpportunityId = :System.currentPageReference().getParameters().get('Id')];
      
      if(totalCount == 0)
      {
          showButtons = false;
          ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Unable to locate an ActiveBatch Execution Agent product line item in this opportunity.'));
          return null;
      }
      
      if(totalCount > 1)
      {
          showButtons = false;
          ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,totalCount + ' ActiveBatch Execution Agent product line items were found in this opportunity.  Unfortunately the line-item splitter only works when a single Execution Agent line item is present in the opportunity.  To remedy the problem make sure that only one \"Execution Agent\" line item is present in your opportunity.  If you feel this is a SalesForce error, please contact your SalesForce administrator.'));
         
          return null;
      }
     
      OpportunityLineItem A;
      A = [SELECT Id, Quantity, PricebookEntryID, TotalPrice, UnitPrice, ListPrice, Description  FROM OpportunityLineItem WHERE PricebookEntry.Name LIKE '%Execution Agent%' AND OpportunityId =  :System.currentPageReference().getParameters().get('Id')];     
     PricebookEntryID = A.PricebookEntryId;	
       
      pointsTotal = Integer.valueOf(A.Quantity);
      points = Integer.valueOf(A.Quantity);
      unitPrice = Integer.valueOf(A.UnitPrice);
      listPrice = Integer.valueOf(A.ListPrice);
       
       return A;
  }  
    
     public OpportunityLineItem updateOpps() { 
          Integer lineCount = 2;
         OpportunityLineItem A;
      A = [SELECT Id, Quantity, PricebookEntryID, TotalPrice, UnitPrice, ListPrice, Description  FROM OpportunityLineItem WHERE PricebookEntry.Name LIKE '%Execution Agent%' AND OpportunityId =  :System.currentPageReference().getParameters().get('Id')];     

         A.Quantity = Integer.valueOf(linePak);
         A.TotalPrice = (Decimal.valueOf(unitPrice) * Integer.valueOf(linePak));

         update A; 
         
          while (lineCount <= Integer.valueOf(lineQty)) {         
         OpportunityLineItem OLI = new OpportunityLineItem();
         OLI.OpportunityId = System.currentPageReference().getParameters().get('Id');
         OLI.PricebookEntryId = priceBookEntryId; //PriceBookEntry Id for that Product should be assigned.
         OLI.Quantity = Integer.valueOf(linePak);
         OLI.TotalPrice = (Decimal.valueOf(unitPrice) * Integer.valueOf(linePak));
         OLI.Description = description;
         insert OLI;
             lineCount++;
         }
     
         return null;
  }   
    
     public OpportunityLineItem createNewOpps() {
         
         Integer lineCount = 1;
         
         while (lineCount <= Integer.valueOf(lineQty)) {         
         OpportunityLineItem OLI = new OpportunityLineItem();
         OLI.OpportunityId = System.currentPageReference().getParameters().get('Id');
         OLI.PricebookEntryId = priceBookEntryId; //PriceBookEntry Id for that Product should be assigned.
         OLI.Quantity = Integer.valueOf(linePak);
         OLI.TotalPrice = (Decimal.valueOf(unitPrice) * Integer.valueOf(linePak));
         OLI.Description = description;
         insert OLI;
             lineCount++;
         }
     
         return null;
  }   
}
Attempted Test Class

    @isTest
public class testSplit { 
    
    @isTest static void testSplit()   {
        //Account acct = new Account(Name='Test Account');
        Account acct = new Account(Name='Test Account', Sales_Tax__c=2, Wire_Fee__c=25);
       
System.debug('Start enter contact');        
        Contact contact = new Contact(Email = 'test@test.com', Marketing_Qualified_Action__c = 'Option1', FirstName = 'Test', LastName= 'Tester', AccountId = acct.Id);
        insert contact; 
        
      

 System.debug('Start enter opportunities');       
        Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',  StageName='Closed Won',Support_Amount__c =20, VUP_Amount__c = 20, Sales_Tax__c=2, Wire_Fee__c =20, Prorated_Amount__c =100.00, CloseDate=System.today().addMonths(1), AccountId=acct.Id);
        insert opp;
       
         Opportunity opp2 = new Opportunity(Name=acct.Name + ' Opportunity', StageName='Prospecting',  Support_Amount__c =20, VUP_Amount__c = 20, Sales_Tax__c=2, Wire_Fee__c =20, Prorated_Amount__c =100.00, CloseDate=System.today().addMonths(1), AccountId=acct.Id);
        insert opp2;
        
 Id pricebookId = Test.getStandardPricebookId();       
        //Create your product
Product2 prod = new Product2(Name = 'Execution Agent Points',  ProductCode = 'Pro-X', isActive = true, ProductFamilyID__c=173, Invoice_Description__c='test');
insert prod;

//Create your pricebook entry
PricebookEntry pbEntry = new PricebookEntry(Pricebook2Id=pricebookId, Product2Id = prod.Id,  UnitPrice = 100.00, IsActive = true);
insert pbEntry;
        
         //SELECT Id, Quantity, PricebookEntryID, TotalPrice, UnitPrice, ListPrice, Description  FROM OpportunityLineItem WHERE PricebookEntry.Name LIKE '%Execution Agent%' AND OpportunityId =  :System.currentPageReference().getParameters().get('Id')
       OpportunityLineItem opline = new OpportunityLineItem(PricebookEntryId=pbEntry.Id, OpportunityId=opp.Id, Quantity=20,TotalPrice=20  * pbEntry.UnitPrice);
        insert opline;
            
             OpportunityLineItem opline2 = new OpportunityLineItem(PricebookEntryId = pbEntry.Id, OpportunityId= opp2.Id, Quantity=20,TotalPrice = 20  * pbEntry.UnitPrice);
        insert opline2;
            
             OpportunityLineItem opline3 = new OpportunityLineItem(PricebookEntryId = pbEntry.Id, OpportunityId= opp.Id, Quantity=20,TotalPrice = 20  * pbEntry.UnitPrice);
        insert opline3;
        
        
  System.debug('Start enter test');   
        
        // Perform test
        Test.startTest();
			ApexPages.currentPage().getParameters().put('id', String.valueOf(opp.Id));
			SplitExecutionAgentController  testAccPlan = new SplitExecutionAgentController();
			testAccPlan.updateOpps();
			testAccPlan.createNewOpps ();
        
        	ApexPages.currentPage().getParameters().put('id', String.valueOf(opp2.Id));
			SplitExecutionAgentController  testAccPlan2 = new SplitExecutionAgentController();
			testAccPlan2.updateOpps();
			testAccPlan2.createNewOpps ();

		Test.StopTest();
       
   


    }



}


 
Best Answer chosen by Ty Whitfield
Ty WhitfieldTy Whitfield
A little more on the problem after much debugging.  The issue appears to be with the updateOpps() method.  The "linePak" variable is null in my test case 
<apex:param name="firstParam" assignTo="{!linePak}" value="" />

I was able to fix this by setting the variable like 
testAccPlan.linePak = 20;

Now, I'm just working on total code coverage