+ Start a Discussion
Eric Anderson 54Eric Anderson 54 

Delete process works with page but not with test class

So, I'm new to Apex and Visualforce, and I have a unique problem that I am sure is indicative of the fact that I am a rookie at this envrionment. The code executes correctly when using 'Visualforce' but not with my Apex Test Class. Since I've only been working with Apex and Visualforce for two weeks now, I'm sure its because there is something that I am not clear about. Please find below my Visualforce code, my Controller code and my Test class. I'm only having a problem with testing the Delete code in the Apex class. I can't seem to get the correct 'ID' to pass through so that the row is subsiquently deleted from Salesforce. The 'Null' portion of the Delete in the Controller tests with the Test class, but the deletion of the row inserted does not. Any help would be greatly appreciated. Thanks!

VISUALFORCE CODE 
<apex:page standardController="Request__c" extensions="TrController" >
    <!-- The following code will fix a problem with the calendar autospawning when the time entries are displayed. -->
    <script>
        function setFocusOnLoad(){ Coment.focus(); }
    </script>
   
    <!--Because we will be defining 'Input' fields, we must wrap our code in a 'Form' block. -->
    <apex:form id="Time_Entry_Form">
        <apex:pageBlock title="CDCR - Salesforce Time Reporting for Requests" id="Time_Entry_List">
           
            <!-- The following pageBlockButtons segment defines the two buttons that appear at the top of the Time entry form. -->
            <apex:pageBlockButtons id="Button_area">
                <!-- The following Button is defined in a more complicated fashion so that a parameter can be passed. -->
                <apex:commandLink >
                    <a href="javascript: CurrRequest('{!Request__c.Id}');" class="btn">New</a>               
                </apex:commandLink>
               
                <apex:commandLink >
                    <a href="javascript: SaveEntry();" class="btn">Save</a>               
                </apex:commandLink>

            </apex:pageBlockButtons>
           
             <!-- The following pageBlockTable segment defines the time entry rows that will be displayed. -->
            <apex:pageBlockTable value="{!TimeEntries}" var="entry" id="Entry_Table_List">
                <apex:column width="45" headerValue="Action">
                    <a href="javascript:if (window.confirm('Are you sure?')) DeleteEntry('{!entry.Id}');" style="font-weight:bold">Del</a>               
                </apex:column>   
                <apex:column width="70" headerValue="Activity">
                    <apex:inputField value="{!entry.Activity__c}"/>
                </apex:column>   
                <apex:column width="70" headerValue="Date Worked">
                    <apex:inputField value="{!entry.Date_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Hours">
                    <apex:inputField value="{!entry.Hours_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Worked">
                    <apex:inputField value="{!entry.Minutes_Worked__c}"/>
                </apex:column>   
                <apex:column headerValue="Work Description">
                    <apex:inputField style="width:100%" value="{!entry.Work_Description__c}" id="comment"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <!-- This action block is executed based on the 'Delete' button being clicked on. -->
        <apex:actionFunction action="{!del}" name="DeleteEntry" reRender="Time_Entry_List">
            <apex:param name="deleteEntryID" value="" assignTo="{!SelectedEntryID}"/>
        </apex:actionFunction>
       
         <!-- This action block is executed based on the 'New' button being clicked on. -->
        <apex:actionFunction action="{!add}" name="CurrRequest" reRender="Time_Entry_List">
            <apex:param name="addEntryID" value="" assignTo="{!ReqID}"/>
        </apex:actionFunction>

         <!-- This action block is executed based on the 'Save' button being clicked on. -->
        <apex:actionFunction action="{!save}" name="SaveEntry" reRender="Time_Entry_List"/>
       
     </apex:form>
    <!-- The following script code is used in order to fix the problem with the calendar autospawning. -->
    <script>
        var Coment=document.getElementById('{!$Component.theForm.block.sec.item.comment}');
    </script>   
</apex:page>

APEX CONTROLLER CLASS

public with sharing class TrController
{
    //This is the list for handling the group of time entries related to the parent object.
    public List<Time_Entry__c> TimeEntries {get;set;}
    //Used to get a hold of the entry record that is selected for deletion.
    public string SelectedEntryID {get;set;}
    //Used to get the parent request object ID from the Visual force page to the controller.
    public string ReqID {get;set;}
    public TrController(ApexPages.StandardController controller)
    {
        //Obtain the parent object Id from the the visualforce form.
        ReqId = Apexpages.currentPage().getparameters().get('Id');
        //SelectedEntryId = Apexpages.currentPage().getparameters().get('deleteEntryId');
        //Call the loaddata method to laod the time entries related to the parent object.
        LoadData();
     }
    public void LoadData()
    {
        //Obtain the first 15 bytes of the Parent Object ID to use for record selection.
        string RequestID = ReqId.substring(0, 15);
        //Load the related time entry records from the database.
        TimeEntries = [select id, Activity__c, Date_Worked__c, Hours_Worked__c, Minutes_Worked__c, Work_Description__c from Time_Entry__c WHERE Related_Object__c=:RequestID order by ID DESC];

    }
    public void save()
    {
        //Update the Salesforce database with the data entred.
        update TimeEntries;
    }
    public void add()
    {  
       //Obtain the first 15 bytes of the Parent Object ID to use for record identification.
        string RequestID = ReqId.substring(0, 15);
        //Build the default values to the new time entry record.
        Time_Entry__c entry = new Time_Entry__c(Activity__c='Research', Date_Worked__c=System.today(), Hours_Worked__c=' 0', Minutes_Worked__c='00', Related_Object__c=RequestID);
        //Insert the new default time entry row into the Salesforce database.
        Insert entry;
        //Call the method to reload the Visualforce list.
        LoadData();
    }
    public void del()
    {
     ExecuteDelete(SelectedEntryId);
    }
    public void ExecuteDelete(string selectedEntry)
    {
        //if we are missing the reference, then do nothing except return.
        if (selectedEntry == null)
        {
            return;
        }
        
        //If the record is within the collection, then delete it.
        Time_Entry__c tobeDeleted = null;
        for(Time_Entry__c a : TimeEntries)
        {
            string EntID = a.Id;
            string SelId = EntId.substring(0, 15);
        if (EntID == selectedEntry)
            {
                tobeDeleted = a;
                break;
            }
        }   
        //If account record found then delete it.
        if (tobeDeleted != null)
            {
                Delete toBeDeleted;
            }
        //Refresh the list
        LoadData();

    }

}

APEX TEST CLASS

@isTest
public class TrControllerTest
{
 static testMethod void testMethod1()
 {
  
    //Instantiate a new instance of the Custom Request Object.
        Request__c ReqObj = new Request__c();
    //Populate the name of the new request object.
        ReqObj.Name = 'Test request';
    //Populate 'What is being requested.
        ReqObj.What_is_being_requested__c = 'Entry to test apex code.';
    //Insert the new request object into Salesforce.
  insert ReqObj;             
  
 //Instantiate a new instance of the Time_Entry object.
  Time_Entry__c te = new Time_Entry__c();
    //Populate the required fields of the Time Entry object.
  te.Name ='Test';            
        te.Date_Worked__c = System.today();
        te.Hours_Worked__c = '01';
        te.Minutes_Worked__c = '15';
        te.Work_Description__c = 'This is a test entry';
        te.Activity__c = 'Research';
    //Insert the new Time_Entry object into Salesforce.
  insert te;              
  
    //Indicate the starting of the test process.
        Test.StartTest();
 
    //Post the Request ID of the Request object created.
            Apexpages.currentPage().getparameters().put('id', String.valueOf(ReqObj.Id));
    //Instantiate a new instance of the Request object standard controller.
       ApexPages.StandardController sc = new ApexPages.StandardController(ReqObj);
    //Instantiate a new instance of the Time Entry Controller that is related to the Standard controller.
        TrController testAccPlan = new TrController(sc);
   
    //Test the code within the 'save' method.
            testAccPlan.save(); 
    //Test the code within the 'add' method.
         testAccPlan.add();           
         //System.AssertEquals(NewEntryId, ReqObj.Id);
            
 //Obtain the object Id's for the row inserted in the database initially.    
         List<Time_Entry__c> deleteEntry = [select id from Time_Entry__c WHERE Work_Description__c = 'This is a test entry'];

 //Loop through the objects returned from the 'Select' statement and pass the Object Id's to the 'ExecuteDelete' class.    
        for(Time_Entry__c a : deleteEntry)
            {
                testAccPlan.ExecuteDelete(a.Id);
                //Leave the loop after one itteration.
                break;
            }
    
    //Execute the ExecuteDelete class with a 'Null' variable so that the additionally related code is tested.
        testAccPlan.ExecuteDelete(null);
  
    //Indicate the end of the test code.
        Test.StopTest();
 }
}
Best Answer chosen by Eric Anderson 54
Amit Chaudhary 8Amit Chaudhary 8
Please try to update  your code like below
@isTest
public class TrControllerTest
{
	static testMethod void testMethod1()
	{
  
		Request__c ReqObj = new Request__c();
			ReqObj.Name = 'Test request';
			ReqObj.What_is_being_requested__c = 'Entry to test apex code.';
		insert ReqObj;             

		Time_Entry__c te = new Time_Entry__c();
			te.Name ='Test';            
			te.Date_Worked__c = System.today();
			te.Hours_Worked__c = '01';
			te.Minutes_Worked__c = '15';
			te.Work_Description__c = 'This is a test entry';
			te.Activity__c = 'Research';
		//Insert the new Time_Entry object into Salesforce.
		insert te;              
  
        Test.StartTest();
 
			Apexpages.currentPage().getparameters().put('id', String.valueOf(ReqObj.Id));
			ApexPages.StandardController sc = new ApexPages.StandardController(ReqObj);
			TrController testAccPlan = new TrController(sc);
            testAccPlan.save(); 
			testAccPlan.add(); 
			testAccPlan.SelectedEntryID = te.id;
    
			testAccPlan.del();
  
		Test.StopTest();
	}
}

Let us know if this will help you
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please try to update  your code like below
@isTest
public class TrControllerTest
{
	static testMethod void testMethod1()
	{
  
		Request__c ReqObj = new Request__c();
			ReqObj.Name = 'Test request';
			ReqObj.What_is_being_requested__c = 'Entry to test apex code.';
		insert ReqObj;             

		Time_Entry__c te = new Time_Entry__c();
			te.Name ='Test';            
			te.Date_Worked__c = System.today();
			te.Hours_Worked__c = '01';
			te.Minutes_Worked__c = '15';
			te.Work_Description__c = 'This is a test entry';
			te.Activity__c = 'Research';
		//Insert the new Time_Entry object into Salesforce.
		insert te;              
  
        Test.StartTest();
 
			Apexpages.currentPage().getparameters().put('id', String.valueOf(ReqObj.Id));
			ApexPages.StandardController sc = new ApexPages.StandardController(ReqObj);
			TrController testAccPlan = new TrController(sc);
            testAccPlan.save(); 
			testAccPlan.add(); 
			testAccPlan.SelectedEntryID = te.id;
    
			testAccPlan.del();
  
		Test.StopTest();
	}
}

Let us know if this will help you
 
This was selected as the best answer
Eric Anderson 54Eric Anderson 54
Amit, Thank you for the suggestion, but I had already tried that. It turned out that I had a bug in my test code in that I was not emulating the way a new record should have been created correctly. My code should have included a 'Related object' id in the insert into the Time entry record.

Thank you for your efforts!